Java Concurrency by Comparison

Concurrency is hard, especially protecting shared memory. As soon as two threads read and write the same data, code that looks perfectly fine can lose updates, see stale values, or deadlock, and these bugs rarely show up in a quick test run.

In the comparisons below, we take two everyday data structures, a counter and a collection, that are neither protected nor documented, and make them safe to use in a concurrent environment, one small step at a time. Each step shows the code before and after, and explains what the change protects against and what it costs:

  • Chapter 1 starts with synchronized, documents the thread-safety guarantees, and moves on to explicit, well-scoped, hidden, and fair locks. It ends with AtomicLong, which avoids locks altogether, and LongAdder, which spreads the updates when many threads count at once.
  • Chapter 2 does the same for collections: from guarding a plain ArrayList yourself, to synchronized wrappers, to the concurrent collections of java.util.concurrent.
  • Chapter 3 turns to newer tools: virtual threads, which run thousands of blocking tasks without a carefully sized thread pool, structured concurrency, which treats related tasks as one unit of work, and scoped values, a safer replacement for ThreadLocal.

The world of concurrency certainly encompasses much more, from executors and parallel streams to the fork/join framework. But in practice, protecting such shared data structures correctly is what most everyday Java code needs. The comparisons follow the same before/after format as the book Java by Comparison and are free to read.