Software engineering · java · concurrency · multithreading · jvm · performance
Java Concurrency Without the Headaches
How Java concurrency works, from starting a thread and fixing a race condition to synchronized, volatile, atomics, concurrent collections, executors and CompletableFuture, down to the memory model, lock internals, false sharing, deadlocks, thread pools and virtual threads, explained from the basics up to what senior engineers need to know.
One kitchen, several cooks
Picture a restaurant kitchen with one cook. Orders come in, the cook makes them one at a time, and nothing ever goes wrong between two dishes. It is also slow: while the pasta water boils, the cook stands and waits.
Hire three more cooks and the kitchen gets faster, but new problems arrive with them. Two cooks reach for the last onion at the same moment. One cook writes “out of salt” on the whiteboard, and another, who looked at the board a minute ago, never sees it. Two cooks each hold one of the two knives the recipe needs and wait for the other to put theirs down, forever.
Those are the three problems of concurrent programming, and Java has names for all of them: race conditions, visibility and deadlock. A thread is a cook. The heap, where your objects live, is the shared kitchen. Everything in java.util.concurrent, and every rule in the Java Memory Model, exists to let several cooks share one kitchen without ruining dinner.
// One cook: everything happens in order
for (Order order : orders) {
cook(order);
}
// Several cooks: an executor hands orders to a pool of threads
try (ExecutorService kitchen = Executors.newFixedThreadPool(4)) {
for (Order order : orders) {
kitchen.submit(() -> cook(order));
}
} // close() waits for every order to finish (Java 19)
The second version is four times faster when cook spends its time waiting, and silently wrong the moment two orders touch the same object without protection. This article starts with the everyday tools, threads, executors, locks and concurrent collections, and goes down to what senior engineers need: the happens-before rules, safe publication, how synchronized and compare-and-swap work in the hardware, false sharing, how a ThreadPoolExecutor really decides what to do with a task, deadlock diagnosis and virtual threads. It continues the series after Java I/O and NIO, Demystified.
The basics: threads and tasks
A thread is an independent path of execution with its own call stack. Every Java program starts with one, the main thread, and can start more:
Thread worker = new Thread(() -> {
System.out.println("hello from " + Thread.currentThread().getName());
});
worker.start(); // runs the lambda on a new thread
worker.join(); // wait for it to finish
Call start(), not run(). Calling run() directly just executes the lambda on the current thread, like any other method call, and is a classic first mistake.
The lambda is a Runnable, a task that returns nothing. If the task produces a value, it is a Callable<V>, which can also throw checked exceptions. Both were covered as functional interfaces in Java Lambdas and Functional Interfaces.
Don’t manage threads by hand: use an executor
Creating a Thread for every piece of work has two problems. A platform thread is expensive: it is a real operating system thread, with a stack the OS reserves (about 1 MB by default on 64-bit Linux), and creating one takes tens of microseconds. And nothing limits how many you create, so a burst of work can create thousands of them.
An executor separates what to run (a task) from how it runs (which thread, when, how many at once). You submit tasks, and you get back a Future, a handle on a result that will exist later:
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
Future<Integer> answer = pool.submit(() -> slowComputation()); // a Callable
doSomethingElse();
int result = answer.get(); // blocks until the result is ready
}
Future.get() waits for the task. If the task threw an exception, get() throws an ExecutionException with the original as its cause; the exception doesn’t disappear, but it doesn’t show up until someone calls get(). A task submitted with submit whose Future nobody reads can fail without anyone ever knowing.
Since Java 19, ExecutorService is AutoCloseable, and close() shuts the pool down and waits for submitted tasks to finish. Before that, you had to call shutdown() and awaitTermination() yourself, and a forgotten shutdown() kept the JVM alive because the pool’s threads were still running.
The factory methods on Executors give you the common shapes:
| Factory | What it creates | Watch out for |
|---|---|---|
newFixedThreadPool(n) |
n threads sharing one queue |
The queue is unbounded: work piles up in memory if tasks arrive faster than they finish |
newCachedThreadPool() |
A new thread whenever none is idle; idle threads die after 60 s | No upper limit on threads |
newSingleThreadExecutor() |
One thread, tasks run in submission order | Same unbounded queue |
newScheduledThreadPool(n) |
Runs tasks after a delay or periodically | An exception in a periodic task silently cancels it |
newVirtualThreadPerTaskExecutor() |
A new virtual thread for every task (Java 21) | Cheap threads, but downstream resources are still limited |
newWorkStealingPool() |
A ForkJoinPool sized to the CPU count |
Meant for CPU-bound, divisible work |
For production services, the “watch out for” column matters more than the convenience. The advanced section shows how to build a ThreadPoolExecutor with explicit limits.
Virtual threads in one paragraph
Java 21 (JEP 444) added virtual threads: threads managed by the JVM instead of the operating system, so cheap that you can create a million. When a virtual thread blocks on I/O, the JVM parks it and runs another one on the same OS thread. The I/O article covered how that works for sockets. For concurrency, the practical rule is simple: for tasks that spend most of their time waiting (HTTP calls, database queries, file reads), use one virtual thread per task and don’t pool them.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (String url : urls) {
executor.submit(() -> fetch(url)); // 10,000 URLs, 10,000 virtual threads: fine
}
}
Virtual threads make waiting cheap. They don’t make shared data safe. Everything in the next sections applies to them exactly as it applies to platform threads.
Why it goes wrong: the race condition
Here is the shortest broken concurrent program:
class Counter {
private int count = 0;
void increment() { count++; }
int get() { return count; }
}
Counter counter = new Counter();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int i = 0; i < 4; i++) {
pool.submit(() -> {
for (int j = 0; j < 1_000_000; j++) counter.increment();
});
}
}
System.out.println(counter.get()); // expected 4,000,000; printed 2,302,322 on one run
count++ looks like one operation, but it is three: read count into a register, add one, write it back. If two threads both read 41, both add one and both write 42, one increment is lost. This is a race condition: the result depends on how the threads’ steps happen to interleave. Run it again and you get a different wrong number, or occasionally the right one: in three runs on a four-core machine, it printed 2,302,322, then 4,000,000, then 3,436,272. A test that passes once proves nothing.
The lost update is one shape of race. The other common one is check-then-act, where a decision is made on information that is stale by the time you act on it:
if (!cache.containsKey(key)) { // two threads both see "missing"...
cache.put(key, expensiveLoad(key)); // ...and both load it
}
if (account.balance() >= amount) { // two withdrawals both pass the check...
account.withdraw(amount); // ...and the balance goes negative
}
Each line is fine on its own. The bug is the gap between them. The fix in every case is to make the steps atomic: no other thread can see or act on the state halfway through. Java gives you three ways to do that: locks, atomic variables and concurrent collections that offer the compound operation as one call.
synchronized: one cook at a time
Every Java object has a built-in lock, called its monitor. A synchronized block takes the lock before it runs and releases it when it exits, normally or with an exception. Only one thread can hold a given monitor at a time; the others wait at the door:
class Counter {
private int count = 0;
synchronized void increment() { count++; } // locks on 'this'
synchronized int get() { return count; }
}
A synchronized method locks this; a static synchronized method locks the Class object. A block lets you choose the lock and keep the protected section small:
class Inventory {
private final Object lock = new Object();
private final Map<String, Integer> stock = new HashMap<>();
boolean reserve(String item, int qty) {
synchronized (lock) { // check and act, together
int available = stock.getOrDefault(item, 0);
if (available < qty) return false;
stock.put(item, available - qty);
return true;
}
}
}
Three rules make synchronized work:
- Every access to the shared state must hold the same lock, reads included. A synchronized
incrementwith an unsynchronizedgetis still broken, for reasons the next section explains. - Lock on a private, final object. Locking on
thislets outside code lock the same object and interfere. Never lock on aStringliteral or a boxedInteger: they are shared across the whole JVM, so unrelated code can end up sharing your lock. - Keep the critical section short. Don’t call slow I/O or unknown code (a callback, a listener) while holding a lock. The first makes everyone wait; the second is how deadlocks start.
Java monitors are reentrant: a thread that holds a lock can take it again, so a synchronized method can call another synchronized method on the same object without blocking itself.
wait and notify
Monitors also let threads wait for a condition. wait() releases the lock and sleeps until another thread calls notify() or notifyAll() on the same object:
synchronized (lock) {
while (queue.isEmpty()) { // always a loop, never an if
lock.wait();
}
return queue.remove();
}
The loop is required. A thread can wake up without being notified (a spurious wakeup, which the specification allows), or another thread can take the item first. In modern code you rarely write wait and notify yourself: a BlockingQueue or a CountDownLatch does the same job with less room for error. They are worth recognising in older code.
Visibility: the flag nobody sees
This program looks harmless, and on many JVMs it never stops:
class Worker {
private boolean running = true;
void run() {
while (running) {
// busy work that doesn't touch 'running'
}
System.out.println("stopped");
}
void stop() { running = false; }
}
Worker worker = new Worker();
new Thread(worker::run).start();
Thread.sleep(1000);
worker.stop(); // the worker thread may spin forever
There is no race on running: only one thread writes it, and a boolean write can’t be half done. The problem is visibility. Without synchronization, nothing obliges the worker to ever see the main thread’s write. The JIT compiler sees a loop that never changes running, reads the field once, and turns the loop into while (true). On this machine’s Java 21, the program above hangs.
Hardware adds its own reasons. Each CPU core has its own caches and a store buffer, and a write may sit in one core’s store buffer before other cores can see it. Both the compiler and the CPU are allowed to reorder memory operations, as long as the reordering can’t be observed by the thread doing it. Other threads can observe it.
volatile
Marking the field volatile fixes it:
private volatile boolean running = true;
A volatile field is never cached in a register across reads; every read sees the most recent write by any thread. More importantly, as the advanced section explains, a volatile write and a later volatile read of the same field act as a fence: everything the writer did before the write is visible to the reader after the read.
volatile gives visibility and ordering. It doesn’t give atomicity: volatileCount++ is still read, add, write, and still loses updates. Use volatile for flags and for publishing a reference that one thread sets and others read. Use a lock or an atomic for anything that reads and then writes.
synchronized also guarantees visibility. Releasing a monitor publishes everything the thread wrote inside it, and acquiring the same monitor sees it. That is why the unsynchronized get in the counter example is broken: without taking the lock, the reader has no guarantee of seeing the writes made under it.
Atomic variables: lock-free counters
For a single variable, the classes in java.util.concurrent.atomic give you atomic compound operations without a lock:
AtomicInteger count = new AtomicInteger();
count.incrementAndGet(); // atomic count++
count.addAndGet(5);
count.updateAndGet(x -> Math.min(x * 2, 1_000));
count.compareAndSet(10, 0); // set to 0 only if it is currently 10
AtomicReference<Config> config = new AtomicReference<>(Config.defaults());
config.set(Config.load()); // publish a new immutable snapshot
They are built on a CPU instruction called compare-and-swap (CAS), covered in the advanced section. The function you pass to updateAndGet or accumulateAndGet may run more than once if another thread wins the race, so it must be free of side effects.
When many threads update one counter, use LongAdder instead of AtomicLong. It spreads updates over several internal cells so threads don’t fight over one memory location, and adds them up when you call sum():
LongAdder requests = new LongAdder();
requests.increment(); // from any number of threads, cheaply
long total = requests.sum(); // not an atomic snapshot while updates continue
On a contended counter, LongAdder is often several times faster: with four threads each adding five million times, it took about 60 ms against roughly 700 ms for AtomicLong on a four-core machine. It is the right tool for statistics and metrics, and the wrong one when you need an exact value to make a decision, such as “allocate ID number n”.
Concurrent collections
The collections from Understanding Java Collections, ArrayList, HashMap and the rest, are not thread-safe. Two threads writing a HashMap can lose entries or corrupt its internal table; in Java 7 and earlier a concurrent resize could even create a cycle in a bucket’s linked list, so that a later get looped forever.
The old fix, Collections.synchronizedMap(map), wraps every method in one lock. That makes single calls safe, but compound operations are still races, iteration must be locked by hand, and every thread queues for the same lock. java.util.concurrent has better options.
ConcurrentHashMap
ConcurrentHashMap lets many threads read and write at once. Reads take no lock. A write locks only the one bucket it changes, so writes to different keys rarely collide. More useful than the speed are its atomic compound methods, which replace check-then-act:
ConcurrentHashMap<String, Long> hits = new ConcurrentHashMap<>();
hits.merge(page, 1L, Long::sum); // atomic "add one, or start at 1"
Map<String, Report> cache = new ConcurrentHashMap<>();
Report r = cache.computeIfAbsent(key, k -> loadReport(k)); // loads at most once per key
hits.compute(page, (k, v) -> v == null ? 1 : v + 1); // arbitrary atomic update
A few rules come with it:
- No
nullkeys or values. In a concurrent map,getreturningnullmust mean “absent”; there is no way to tell “absent” from “mapped to null” atomically. - Keep the functions passed to
compute*andmergeshort, and never let them modify the same map. They run while the bucket is locked; a slow function blocks other writers to that bucket, and a recursive update can deadlock or throw. size()and iteration are snapshots of a moving target. Iterators never throwConcurrentModificationException, but they may or may not reflect changes made while they run.- Combine calls and you are back to a race.
if (!map.containsKey(k)) map.put(k, v)on aConcurrentHashMapis exactly as broken as on aHashMap. UseputIfAbsentorcomputeIfAbsent.
The rest of the toolbox
| Class | Use it for |
|---|---|
ConcurrentHashMap |
The default shared map |
ConcurrentSkipListMap, ConcurrentSkipListSet |
A sorted concurrent map or set, the thread-safe TreeMap |
CopyOnWriteArrayList |
Lists read constantly and changed rarely, such as listener lists: every write copies the array |
ConcurrentLinkedQueue |
A non-blocking, unbounded FIFO queue |
ArrayBlockingQueue |
A bounded queue between producers and consumers |
LinkedBlockingQueue |
Same, optionally bounded; unbounded by default |
SynchronousQueue |
A hand-off with no capacity: each put waits for a take |
PriorityBlockingQueue, DelayQueue |
Ordered by priority, or released after a delay |
Producers and consumers with a BlockingQueue
A BlockingQueue is the simplest safe way for threads to pass work to each other. put waits when the queue is full and take waits when it is empty, so the queue also applies back-pressure: fast producers are slowed to the consumers’ pace instead of filling memory.
BlockingQueue<Order> orders = new ArrayBlockingQueue<>(100);
// producer
Thread.ofPlatform().start(() -> {
for (Order o : incoming()) {
orders.put(o); // waits if 100 orders are already queued
}
});
// consumer
Thread.ofPlatform().start(() -> {
while (true) {
Order o = orders.take(); // waits until an order arrives
cook(o);
}
});
No locks, no wait/notify, no visibility bugs: the queue handles all of it, and every object passed through it is safely visible to the thread that takes it.
Immutability: the problem you don’t have
The easiest shared state to get right is state that never changes. An immutable object can be shared between any number of threads with no locking at all, because there is nothing to race on:
public record Money(String currency, long cents) {
public Money plus(Money other) {
return new Money(currency, cents + other.cents); // a new object, never a change
}
}
Records, String, LocalDate, BigDecimal and the collections from List.of and Map.of are all immutable. A common design is an immutable snapshot behind an AtomicReference or a volatile field: readers grab the current snapshot without locks, and a writer builds a new one and swaps it in. Configuration, routing tables and feature flags fit this shape well.
Some classes look harmless and aren’t: SimpleDateFormat keeps parsing state in fields, so sharing one between threads produces wrong dates. Its replacement, DateTimeFormatter, is immutable.
Composing asynchronous work: CompletableFuture
Future.get() blocks, so a Future can’t express “when this finishes, do that”. CompletableFuture (Java 8) can. It is a future you can chain, combine and complete from anywhere:
ExecutorService io = Executors.newVirtualThreadPerTaskExecutor();
CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> fetchUser(id), io);
CompletableFuture<Order> orders = CompletableFuture.supplyAsync(() -> fetchOrders(id), io);
CompletableFuture<Page> page = user
.thenCombine(orders, Page::new) // when both are done
.thenApply(Page::withRecommendations) // transform the result
.completeOnTimeout(Page.fallback(), 2, TimeUnit.SECONDS)
.exceptionally(e -> Page.error(e)); // recover from any failure above
render(page.join());
The method names follow a pattern:
| Method | Like | Use when the next step… |
|---|---|---|
thenApply(f) |
map |
is a plain function of the result |
thenCompose(f) |
flatMap |
itself returns a CompletableFuture |
thenCombine(other, f) |
zip | needs the results of two futures |
thenAccept(c), thenRun(r) |
forEach |
consumes the result, or just runs afterwards |
exceptionally(f), handle(f) |
catch |
must recover from, or inspect, a failure |
allOf(...), anyOf(...) |
waits for all, or the first, of many futures |
The map and flatMap names are the same idea as in The Java Streams API, and the reason is the same: a step that returns another future would otherwise give you a CompletableFuture<CompletableFuture<T>>.
Two traps catch almost everyone:
- The default pool.
supplyAsync(task)without an executor runs onForkJoinPool.commonPool(), which has only (CPU count − 1) threads and is shared with parallel streams across the whole JVM. Put blocking calls there and you starve everything else that uses it. Always pass an executor for I/O. - Swallowed exceptions. A failure inside a stage travels down the chain as an exceptional completion. If no stage handles it and nobody calls
join()orget(), it is never logged. End every chain with a handler or a join.
Without the Async suffix, a stage like thenApply runs on whichever thread completes the previous stage, or on the calling thread if it is already complete. With it, thenApplyAsync hands the stage to an executor. The non-async form is fine for cheap transformations; use the async form with an explicit executor when the step is slow.
Coordinating threads
A few small classes cover the common “wait for something” patterns:
// CountDownLatch: wait until n things have happened
CountDownLatch ready = new CountDownLatch(3);
for (Service s : services) {
pool.submit(() -> { s.start(); ready.countDown(); });
}
ready.await(); // continues once all three have started
// Semaphore: allow at most n threads in at once
Semaphore dbPermits = new Semaphore(20);
dbPermits.acquire();
try {
queryDatabase();
} finally {
dbPermits.release();
}
| Class | What it does | Reusable? |
|---|---|---|
CountDownLatch |
Threads wait until a count reaches zero | No |
CyclicBarrier |
A fixed group of threads wait for each other, then all continue | Yes |
Phaser |
A barrier whose number of parties can change between phases | Yes |
Semaphore |
Limits how many threads use a resource at once | Yes |
Exchanger |
Two threads swap objects at a meeting point | Yes |
The semaphore is the one that matters most with virtual threads. You can start 10,000 virtual threads, but the database still has 20 connections; a semaphore makes the other 9,980 queue politely instead of failing.
Stopping a thread: interruption
Java has no safe way to kill a thread from the outside. Thread.stop() was deprecated in 1998, because it could leave objects half updated with their locks released, and since Java 20 it just throws UnsupportedOperationException. Instead, Java uses cooperative cancellation: you ask a thread to stop by interrupting it, and the thread checks and stops itself.
Thread worker = Thread.ofPlatform().start(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
Task t = queue.take(); // blocking methods throw when interrupted
process(t);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag, then exit
return;
}
}
});
worker.interrupt(); // a request, not a command
interrupt() sets a flag on the thread. Methods that block, such as sleep, wait, join and BlockingQueue.take, notice it, clear it and throw InterruptedException. Future.cancel(true) and ExecutorService.shutdownNow() work by interrupting the thread running the task.
The rule for InterruptedException: never swallow it. If you can’t rethrow it, call Thread.currentThread().interrupt() to put the flag back, so code further up the stack knows a stop was requested. An empty catch (InterruptedException e) {} is how services end up impossible to shut down.
The mistakes everyone makes
| Mistake | What happens | Fix |
|---|---|---|
count++ on a shared field |
Lost updates | AtomicInteger, LongAdder or a lock |
| Check-then-act across two calls | Two threads both pass the check | One atomic call: computeIfAbsent, putIfAbsent, or a lock around both |
| Locking writes but not reads | Readers see stale or half-built state | Every access holds the same lock |
A stop flag that isn’t volatile |
The loop never sees the change | volatile, or use interruption |
Sharing a HashMap or ArrayList |
Lost entries, corrupted structure | ConcurrentHashMap, CopyOnWriteArrayList, or don’t share |
Locking on this, a String or a boxed number |
Unrelated code shares your lock | A private final Object lock |
| Calling foreign code while holding a lock | Deadlocks, long stalls | Copy what you need, release, then call |
Executors.newFixedThreadPool under unbounded load |
The queue grows until out of memory | A ThreadPoolExecutor with a bounded queue |
Blocking calls in CompletableFuture without an executor |
The common pool starves; parallel streams stall | Pass your own executor |
submit() and never checking the Future |
Exceptions vanish | get() the result, or catch inside the task |
Swallowing InterruptedException |
Threads can’t be cancelled | Restore the flag or rethrow |
wait() in an if |
Spurious wakeups break the logic | wait() in a while loop |
| Assuming more threads means faster | Contention and context switches make it slower | Measure; size pools to the work |
Advanced ideas
Everything so far is enough to write correct concurrent code with the standard tools. The rest of the article is about why those tools work, what they cost, and the problems that only show up under real load.
The Java Memory Model and happens-before
The visibility bug earlier isn’t a quirk; it is what the specification allows. Chapter 17 of the Java Language Specification, rewritten for Java 5 by JSR 133, defines the Java Memory Model (JMM). It doesn’t describe caches or store buffers. It defines one relation, happens-before, and makes one promise: if action A happens-before action B, then B sees everything A did. If neither happens-before the other, and at least one is a write to a shared variable, the program has a data race, and a read may see the newer value, the older one, or (for long and double fields that aren’t volatile) half of each.
These are the happens-before edges you use every day:
- Program order. Within one thread, each action happens-before the next.
- Monitor lock. Releasing a monitor happens-before every later acquisition of the same monitor.
- Volatile. A write to a volatile field happens-before every later read of that field.
- Thread start and join.
t.start()happens-before everything int; everything inthappens-before another thread’st.join()returns. - Executors and concurrent collections. Submitting a task happens-before it runs; a task’s completion happens-before
Future.get()returns; putting an object into a concurrent collection happens-before a thread that retrieves it. These come from thejava.util.concurrentdocumentation, which states them for every class. - Transitivity. If A happens-before B and B happens-before C, then A happens-before C.
Transitivity is what makes the system useful. A volatile write doesn’t just publish the volatile field; it publishes everything the writing thread did before it:
class Handoff {
private int[] data; // plain field
private volatile boolean ready; // the fence
void producer() {
data = new int[] {1, 2, 3}; // (1)
ready = true; // (2) volatile write
}
void consumer() {
if (ready) { // (3) volatile read sees true
use(data); // (4) guaranteed to see {1, 2, 3}
}
}
}
(1) happens-before (2) by program order, (2) happens-before (3) by the volatile rule, and (3) happens-before (4) by program order, so (1) happens-before (4). Remove volatile and there is no chain: the consumer can see ready == true and still read data as null, because the compiler or CPU was free to make the two writes visible in the other order.
This is also why “it works on my machine” means little for concurrent code. x86 processors have a strong memory model and rarely reorder stores, so many races stay hidden on a laptop and appear on ARM servers, such as AWS Graviton, which reorder far more freely.
Safe publication and final fields
Creating an object and sharing it is itself a race unless something orders the two. Publishing an object safely means making sure a thread that sees the reference also sees the object’s fully constructed state. You publish safely by storing the reference:
- in a
staticinitializer (class initialization is locked by the JVM), - in a
volatilefield or anAtomicReference, - in a field guarded by a lock that readers also take, or
- in a concurrent collection, a
BlockingQueueor an executor’s task.
final fields have a special guarantee. Once a constructor finishes, any thread that sees a reference to the object sees the correct values of its final fields, and of everything reachable through them, even if the reference was published through a data race. That makes properly immutable objects (all fields final, nothing changed after construction) safe to share any way you like. The guarantee breaks if the constructor lets this escape, for example by registering itself as a listener before it finishes.
The classic illustration is double-checked locking, which was broken before Java 5 and only works with volatile:
class Registry {
private static volatile Registry instance; // without volatile: broken
static Registry get() {
Registry r = instance;
if (r == null) {
synchronized (Registry.class) {
r = instance;
if (r == null) {
instance = r = new Registry();
}
}
}
return r;
}
}
Without volatile, the write of the reference can become visible before the writes made by the constructor, so another thread can get a non-null instance whose fields are still defaults. You rarely need this pattern. A holder class does the same lazily, with no locking code, by using the JVM’s own class initialization lock:
class Registry {
private static class Holder {
static final Registry INSTANCE = new Registry();
}
static Registry get() { return Holder.INSTANCE; } // initialized on first call
}
What synchronized costs
An uncontended synchronized block is cheap. HotSpot keeps lock state in the object’s header. When a thread takes a free lock, it does one CAS to mark the object as locked by it (a thin or lightweight lock), and one more operation to release it. That costs nanoseconds. Biased locking, an older optimisation that skipped even the CAS when one thread used a lock repeatedly, was disabled by default in Java 15 (JEP 374) and later removed; modern CPUs made CAS cheap enough that its complexity no longer paid off.
Contention is where the cost is. When a second thread finds the lock taken, it spins briefly, then the lock is inflated into a full monitor, a separate structure with a queue of waiting threads, and waiters are parked by the operating system. Parking and waking a thread means a system call and a context switch, a few microseconds each, and the woken thread starts with cold caches. A lock held for 100 nanoseconds but contended by 16 threads can make a service slower than running it on one thread.
The JIT also removes locks it can prove unnecessary. Lock elision drops locking on objects that never escape a thread (a local StringBuffer, say), and lock coarsening merges adjacent synchronized blocks on the same object into one. So micro-benchmarks of synchronized often measure nothing at all.
Explicit locks: ReentrantLock and friends
java.util.concurrent.locks has locks that are objects, with abilities synchronized lacks:
private final ReentrantLock lock = new ReentrantLock();
void transfer() throws InterruptedException {
if (!lock.tryLock(50, TimeUnit.MILLISECONDS)) { // give up instead of waiting forever
throw new BusyException();
}
try {
// critical section
} finally {
lock.unlock(); // always in finally: nothing releases it for you
}
}
synchronized |
ReentrantLock |
|
|---|---|---|
| Release | Automatic, even on exception | Manual, in finally |
| Try without blocking, or with a timeout | No | tryLock(), tryLock(timeout) |
| Interruptible wait for the lock | No | lockInterruptibly() |
| Several wait conditions | One per monitor | Any number of Conditions |
| Fairness option | No | new ReentrantLock(true) |
| Shows in thread dumps and JFR | Yes | Yes |
Use synchronized by default; it is shorter and can’t be left locked by mistake. Reach for ReentrantLock when you need a timeout, interruptibility or several conditions. Fair locks hand the lock to the longest waiter, which prevents starvation but costs a lot of throughput, because the lock can’t go to a thread that is already running.
For data that is read far more than written, there are two more:
ReentrantReadWriteLocklets many readers in at once, or one writer. It helps when reads are long; for short reads, the bookkeeping on the shared reader count can make it slower than a plain lock.StampedLock(Java 8) adds optimistic reads: read without locking, then check whether a write happened in the meantime, and retry under a real lock if it did.
private final StampedLock sl = new StampedLock();
private double x, y;
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead(); // no lock taken
double cx = x, cy = y;
if (!sl.validate(stamp)) { // a writer got in: fall back to a read lock
stamp = sl.readLock();
try { cx = x; cy = y; } finally { sl.unlockRead(stamp); }
}
return Math.hypot(cx, cy);
}
StampedLock is fast but sharp: it isn’t reentrant, and the code between the optimistic read and validate must cope with inconsistent values without throwing.
Compare-and-swap and lock-free algorithms
Atomics and much of java.util.concurrent rest on one instruction. Compare-and-swap takes a memory location, an expected value and a new value, and atomically writes the new value only if the location still holds the expected one. It reports whether it succeeded. On x86 it is LOCK CMPXCHG; on ARM, a load-exclusive/store-exclusive pair or, on newer cores, a single CAS instruction.
Any atomic update can be built from CAS with a retry loop:
AtomicLong max = new AtomicLong(Long.MIN_VALUE);
void record(long value) {
long current;
do {
current = max.get();
if (value <= current) return;
} while (!max.compareAndSet(current, value)); // someone else changed it: retry
}
This is lock-free: some thread always makes progress, and no thread can block others by being descheduled while holding a lock. It is what updateAndGet does internally. Simple operations get better instructions where the hardware has them: incrementAndGet compiles to a single LOCK XADD on x86, with no loop at all.
Lock-free doesn’t mean free. Every CAS on a contended location forces the cache line to move between cores, and under heavy contention threads spend their time failing and retrying. Lock-free structures also have their own bug, the ABA problem: a value changes from A to B and back to A, and a CAS that expected A succeeds even though the state it was based on is gone. Java’s garbage collector prevents the most common form (a node can’t be freed and reused while you still hold a reference), and AtomicStampedReference pairs a reference with a version number for the rest.
Since Java 9, VarHandle gives library authors CAS and finer-grained memory ordering (acquire, release, opaque) on ordinary fields and array elements, replacing most uses of sun.misc.Unsafe. Application code almost never needs it; the atomic classes are built on it.
False sharing
CPU caches don’t move single variables between cores; they move cache lines, usually 64 bytes. If two variables share a line and two cores write them, each write invalidates the line in the other core’s cache, even though the threads never touch each other’s data. The line bounces between cores, and two threads that should run independently run as if they shared a lock. This is false sharing.
It shows up in exactly the code people write to avoid contention: an array of per-thread counters, or adjacent fields of a hot object updated by different threads.
long[] perThread = new long[THREADS]; // eight longs fit in one cache line
// thread i does: perThread[i]++ -> all threads fight over the same line
The fix is to keep hot, independently written fields at least a cache line apart. The JDK does this internally with the @jdk.internal.vm.annotation.Contended annotation, which pads a field onto its own line; LongAdder’s cells, Thread’s random-number fields and ConcurrentHashMap’s counter cells all use it. Your own code can use it only with --add-exports and -XX:-RestrictContended, so libraries such as the LMAX Disruptor and JCTools pad manually, with seven unused long fields on each side. Measuring is the only reliable way to find false sharing: Linux perf c2c reports cache lines bouncing between cores.
Deadlock, livelock and starvation
A deadlock needs a cycle: thread 1 holds lock A and waits for B, while thread 2 holds B and waits for A. Neither can continue, ever. The typical cause is two code paths taking the same locks in a different order:
void transfer(Account from, Account to, long amount) {
synchronized (from) {
synchronized (to) { // transfer(a, b) and transfer(b, a) at once: deadlock
from.debit(amount);
to.credit(amount);
}
}
}
The standard fixes, in order of preference:
- Lock ordering. Always take locks in one global order, for example by account ID. A cycle becomes impossible.
- Fewer locks held at once. Copy what you need, release, then call out. Most deadlocks involve a lock held while calling code that takes another.
- Timeouts.
tryLock(timeout)turns a permanent deadlock into a failure you can retry or report.
void transfer(Account from, Account to, long amount) {
Account first = from.id() < to.id() ? from : to;
Account second = from.id() < to.id() ? to : from;
synchronized (first) {
synchronized (second) {
from.debit(amount);
to.credit(amount);
}
}
}
When a deadlock happens in production, a thread dump shows it. jcmd <pid> Thread.print (or jstack <pid>) lists every thread’s stack and the locks it holds and waits for, and ends with “Found one Java-level deadlock” and the exact cycle when there is one. ThreadMXBean.findDeadlockedThreads() does the same check from inside the application, which is useful in a health check.
Two cousins are worth naming. In a livelock, threads aren’t blocked but keep reacting to each other without progress, like two people stepping aside in a corridor in the same direction; random backoff breaks the symmetry. In starvation, a thread can run in principle but never gets the lock or the CPU, because others always win; fair locks and bounded queues address it.
Inside ThreadPoolExecutor
Every Executors.newFixedThreadPool or newCachedThreadPool is a ThreadPoolExecutor with particular settings. Building one yourself lets you choose them, and the order in which it uses them surprises most people:
ThreadPoolExecutor pool = new ThreadPoolExecutor(
8, // core pool size
32, // maximum pool size
60, TimeUnit.SECONDS, // idle time before extra threads die
new ArrayBlockingQueue<>(1_000), // bounded work queue
Thread.ofPlatform().name("orders-", 0).factory(),
new ThreadPoolExecutor.CallerRunsPolicy()); // what to do when everything is full
When a task arrives:
- If fewer than core threads are running, start a new thread for it, even if others are idle.
- Otherwise, put it in the queue.
- If the queue is full and fewer than maximum threads are running, start an extra thread.
- If the queue is full and the pool is at maximum, reject it.
The pool only grows past the core size when the queue is full. With an unbounded queue, as in newFixedThreadPool, the queue is never full, so the maximum is never used and the queue grows until the heap runs out. With a SynchronousQueue, as in newCachedThreadPool, the queue is always full, so every task without an idle thread gets a new one. For a service, use a bounded queue and pick a rejection policy deliberately:
| Policy | On rejection | Good for |
|---|---|---|
AbortPolicy (default) |
Throws RejectedExecutionException |
Failing fast, letting the caller return an error |
CallerRunsPolicy |
Runs the task on the submitting thread | Natural back-pressure: the producer slows down |
DiscardPolicy |
Drops the task silently | Rarely; maybe best-effort telemetry |
DiscardOldestPolicy |
Drops the oldest queued task and retries | Work where only the latest value matters |
Sizing. For CPU-bound work, about one thread per core; more just adds context switches. For work that waits, the classic estimate from Java Concurrency in Practice is threads = cores × (1 + wait time / compute time): a task that waits 90 ms on a database for every 10 ms of CPU needs about ten threads per core to keep the CPUs busy. In practice, the limit is usually a downstream resource, not the CPU, and for waiting-heavy work virtual threads remove the need to guess.
Also give pools a thread factory that names their threads. A thread dump full of pool-7-thread-3 tells you nothing; orders-3 tells you where to look.
ForkJoinPool and work stealing
ForkJoinPool (Java 7) is a different kind of pool, built for tasks that split into subtasks. Each worker thread has its own double-ended queue. A worker pushes the subtasks it creates onto its own deque and takes from the same end (last in, first out, which keeps caches warm). A worker that runs out of work steals from the other end of another worker’s deque, taking the oldest, usually largest, task. Threads rarely touch the same end of the same deque, so there is little contention.
This pool runs parallel streams, as covered in The Java Streams API, the async methods of CompletableFuture without an executor, and the scheduler of virtual threads (a separate instance, with one carrier per core by default). The shared commonPool() is why blocking inside a parallel stream or a default CompletableFuture hurts everyone: there are only as many workers as cores, and a blocked worker is a core doing nothing.
Virtual threads, more closely
A virtual thread is a Thread whose stack lives on the heap as a chunk of objects. The JVM mounts it on a carrier, a platform thread from a dedicated ForkJoinPool, to run it. When it blocks on a lock, a queue, sleep or socket I/O, the JVM unmounts it, copying the active frames off the carrier, and the carrier runs another virtual thread. When the blocking operation completes, the virtual thread is scheduled again, possibly on a different carrier.
The design has consequences:
- Don’t pool virtual threads. Pools exist to amortise thread creation and to limit concurrency. Virtual threads cost about as much as a small object, and limiting concurrency is a semaphore’s job.
ThreadLocalbecomes expensive. A thread-local cache, such as one formatter per thread, made sense with 200 pooled threads. With a million short-lived virtual threads, it makes a million copies and caches nothing.- Pinning. A virtual thread can’t unmount while running native code, and, in Java 21 to 23, while inside a
synchronizedblock. A pinned virtual thread that blocks holds its carrier, and with only one carrier per core, a few of them can stall the scheduler. Java 24 (JEP 491) removed thesynchronizedcase. On 21, preferReentrantLockaround blocking calls, and run with-Djdk.tracePinnedThreads=fullto find offenders. - CPU-bound work gains nothing. Virtual threads aren’t time-sliced; a virtual thread that computes for a second holds its carrier for a second. For CPU work, a pool of platform threads sized to the cores is still right.
Two newer APIs fit this model. Scoped values (ScopedValue, final in Java 25 through JEP 506) replace ThreadLocal for passing context, such as the current user or request ID, down a call tree: the value is immutable and bound for a scope, so it costs nothing to share with child threads. Structured concurrency treats a group of concurrent subtasks as one unit: they start inside a scope, the scope waits for all of them, and if one fails the others are cancelled. It is still a preview API as of Java 25, and its shape has changed between previews; in Java 25 it looks like this:
// Java 25 preview: compile and run with --enable-preview
try (var scope = StructuredTaskScope.open()) {
Subtask<User> user = scope.fork(() -> fetchUser(id));
Subtask<Order> orders = scope.fork(() -> fetchOrders(id));
scope.join(); // waits for both; throws if either failed
return new Page(user.get(), orders.get());
} // leaving the scope cancels anything still running
Compared with the CompletableFuture version earlier, failures cancel siblings automatically, thread dumps show the subtasks under their parent, and the code reads like sequential code.
Measuring and testing concurrent code
Amdahl’s law puts a ceiling on what threads can do. If a fraction s of the work is serial (under a lock, in a single-threaded stage), the best possible speedup on n cores is 1 / (s + (1 − s) / n). With 5% serial work, 16 cores give at most 9.1 times, and no number of cores gets past 20 times. Contention makes the real curve worse, often bending it downwards: past some thread count, adding threads makes the program slower. That point is where to size your pools.
To find out where threads are waiting:
- Thread dumps (
jcmd <pid> Thread.print, a few seconds apart) show which locks threads block on. Many threads inBLOCKEDon the same monitor is a hot lock. For virtual threads,jcmd <pid> Thread.dump_to_file -format=json <file>includes them. - Java Flight Recorder records
jdk.JavaMonitorEnterandjdk.ThreadParkevents with stack traces and durations, showing which locks cost the most total waiting time, with low enough overhead to run in production. - async-profiler in lock mode gives the same as a flame graph.
Testing for races is hard, because a test can pass a million times and the race still exists. Three tools help:
- jcstress, the OpenJDK concurrency stress harness, runs small snippets on many threads in many interleavings and reports every outcome it observed, including the ones the memory model allows but you didn’t expect. It is how the JDK’s own concurrency code is tested.
- Thread-safety by design beats testing: confine state to one thread, make shared state immutable, and use the concurrent classes, so there is little left to test.
- Static analysis such as SpotBugs and Error Prone flags inconsistent synchronization, fields guarded by a lock in some places and not others, and ignored
Futures.
Choosing a tool
| You want to… | Use |
|---|---|
| Run many independent waiting tasks (HTTP, database, files) | Executors.newVirtualThreadPerTaskExecutor() |
| Run CPU-bound tasks | A fixed pool of platform threads, about one per core |
| Run a production pool with limits | ThreadPoolExecutor with a bounded queue, named threads and a rejection policy |
| Count across threads | AtomicLong for exact values, LongAdder for hot statistics |
| Share a map | ConcurrentHashMap with merge, compute and computeIfAbsent |
| Pass work between threads | A bounded BlockingQueue |
| Publish configuration or a snapshot | An immutable object in a volatile field or an AtomicReference |
| Protect several fields that change together | synchronized, or ReentrantLock if you need timeouts |
| Read-mostly data with long reads | ReentrantReadWriteLock or StampedLock |
| Chain or combine asynchronous results | CompletableFuture with an explicit executor, or structured concurrency |
| Limit access to a scarce resource | Semaphore |
| Wait for a set of events | CountDownLatch |
| Signal a thread to stop | interrupt(), and respect InterruptedException |
How Java compares
| Language | Main model | Notable difference |
|---|---|---|
| Go | Goroutines and channels | Cheap threads from the start, and “share memory by communicating” as the idiom; still has a memory model and data races, with a built-in race detector |
| C# | Task, async/await |
Asynchrony is part of the language; virtual threads let Java keep plain blocking code instead |
| Rust | Threads, async with Tokio |
The compiler rejects data races: Send and Sync traits prove at compile time what may be shared |
| Kotlin | Coroutines on the JVM | Structured concurrency built into the language with suspend functions; runs on the same JMM |
| Erlang and Elixir | Processes and messages | No shared memory at all: each process has its own heap, so there are no races on data |
| Python | Threads, asyncio, processes |
The global interpreter lock long kept threads from running Python code in parallel; free-threaded builds (3.13+) are removing it |
Key takeaways
- Concurrency bugs come in three kinds: races (steps interleave), visibility (a write is never seen) and liveness (deadlock, starvation). Each has its own fix.
- Use executors, not raw threads. For waiting-heavy tasks, use virtual threads, one per task, and limit scarce resources with a semaphore.
synchronizedgives atomicity and visibility, but only if every access to the shared state holds the same lock. Lock on private objects and keep critical sections short.volatilegives visibility and ordering, not atomicity. Use it for flags and for publishing immutable snapshots.- Prefer atomics,
ConcurrentHashMapwith its compound methods,BlockingQueueand immutable objects to hand-written locking. - Pass an explicit executor to
CompletableFuture, and make sure every chain handles or surfaces its exceptions. - The memory model is defined by happens-before: locks, volatiles, thread start and join, and the
java.util.concurrentclasses create the edges, and transitivity carries everything written before them. - Under load, the costs are contention, cache-line traffic and context switches. Bound your queues, name your threads, take locks in a fixed order, and measure with thread dumps and JFR before adding threads.
Further reading
- Brian Goetz with Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea, Java Concurrency in Practice (Addison-Wesley), still the best book on the subject; its rules apply unchanged to modern Java
- The Java Language Specification, chapter 17, “Threads and Locks”, which defines happens-before and the final field semantics
- The
java.util.concurrentpackage documentation, whose “Memory Consistency Properties” section lists the happens-before guarantee of every class - Aleksey Shipilëv, “Java Memory Model Pragmatics” and “Close Encounters of The Java Memory Model Kind”, the clearest explanations of what the JMM allows in practice
- Doug Lea, Concurrent Programming in Java and “Using JDK 9 Memory Order Modes”, from the author of most of
java.util.concurrent - JEP 444, “Virtual Threads”; JEP 491, “Synchronize Virtual Threads without Pinning”; JEP 505, “Structured Concurrency”; JEP 506, “Scoped Values”; JEP 374, “Deprecate and Disable Biased Locking”
- The OpenJDK jcstress project, whose sample tests are a guided tour of what the memory model permits