Concurrency: threads and synchronization
Mid-level Always asked 8 min
On this page
The question
What is the difference between synchronized and volatile?
30-second answer
synchronized makes a block mutually exclusive: one thread at a time holds the lock, and releasing it makes its writes visible to the next thread that takes the lock. volatile only makes one variable visible: every read sees the latest write, but nothing is locked, so a read-modify-write like count++ can still lose updates. Use volatile for a flag, synchronized or an atomic class for compound updates.
Understand it
Two threads, one count++
ExploreNo overlap, so nothing is lost this time and count is 2. Nothing stops the steps from interleaving on another run.
View as text
A timeline with one row per time slot. Thread T1 and thread T2 each run count++ once on a shared count that starts at 0, split into read, add and write steps; a third column shows count in memory after each slot, and the result below says whether an update was lost. The drawing is one fixed schedule; a real run varies.
Lost update: Both threads read 0, add 1 and write 1, so count ends at 1 and one update is lost. A real run can lose updates like this.
volatile is not enough: volatile makes writes visible but count++ is still three steps: both threads read 0 and write 1, so one update is lost.
synchronized: The second thread waits for the lock while the first reads, adds and writes, then it reads 1 and writes 2. count is 2. A dashed box shows T2 waiting.
AtomicInteger: The increment is one atomic step, so the threads cannot interleave inside it. count is 2. Each thread has one box instead of three.
With the schedule One after the other, T2 starts after T1 has written, so every protection ends at 2.
A timeline with one row per time slot. Thread T1 and thread T2 each run count++ once on a shared count that starts at 0, split into read, add and write steps; a third column shows count in memory after each slot, and the result below says whether an update was lost. The drawing is one fixed schedule; a real run varies.
Lost update: Both threads read 0, add 1 and write 1, so count ends at 1 and one update is lost. A real run can lose updates like this.
volatile is not enough: volatile makes writes visible but count++ is still three steps: both threads read 0 and write 1, so one update is lost.
synchronized: The second thread waits for the lock while the first reads, adds and writes, then it reads 1 and writes 2. count is 2. A dashed box shows T2 waiting.
AtomicInteger: The increment is one atomic step, so the threads cannot interleave inside it. count is 2. Each thread has one box instead of three.
With the schedule One after the other, T2 starts after T1 has written, so every protection ends at 2.
Takeaway: count++ is three steps: read, add, write. Without a lock or an atomic class, two threads can interleave them and lose an update.
How a deadlock forms, and the fix
Step by stepTwo threads need both locks. T1 takes lock A, then B; T2 takes lock B, then A. Both locks are free.
View as text
Two thread boxes, T1 on the left and T2 on the right, and two lock boxes, A at the top and B at the bottom. A solid line from a thread to a lock means the thread holds it; a dashed arrow means it waits for it. Under each thread is the order in which it takes the locks.
Two threads need both locks. T1 takes lock A, then B; T2 takes lock B, then A. Both locks are free.
T1 takes lock A and holds it.
At the same moment T2 takes lock B. Each thread now holds one lock.
Each thread asks for its second lock, which the other thread holds, so both block and wait.
The waits form a cycle: T1 waits for T2, which waits for T1. It never resolves; findDeadlockedThreads() reports both threads. A ring marks the cycle.
The fix: both threads take A before B. T2 waits for A while T1 holds both, and runs once T1 releases them. No cycle can form. Both threads are now labelled A, then B.
Two thread boxes, T1 on the left and T2 on the right, and two lock boxes, A at the top and B at the bottom. A solid line from a thread to a lock means the thread holds it; a dashed arrow means it waits for it. Under each thread is the order in which it takes the locks.
Two threads need both locks. T1 takes lock A, then B; T2 takes lock B, then A. Both locks are free.
T1 takes lock A and holds it.
At the same moment T2 takes lock B. Each thread now holds one lock.
Each thread asks for its second lock, which the other thread holds, so both block and wait.
The waits form a cycle: T1 waits for T2, which waits for T1. It never resolves; findDeadlockedThreads() reports both threads. A ring marks the cycle.
The fix: both threads take A before B. T2 waits for A while T1 holds both, and runs once T1 releases them. No cycle can form. Both threads are now labelled A, then B.
Takeaway: Two threads taking the same two locks in opposite order can each hold one and wait forever for the other. One lock order for every thread prevents it.
Inside a thread pool
Tap the partsSelect a part to see what it does.
Tap a part to follow a task from submit() through the queue and a worker thread to its Future.
View as text
A thread pool drawn from top to bottom. A caller box submits tasks into a work queue of four slots holding t4 to t7. A fifth task, t8, is marked rejected because the queue is full. Below, three worker threads run t1, t2 and t3, with an arrow from the queue into them. An arrow leads from the workers to a Future box, and a line carries the result from the Future back up to the caller. At the bottom, marks say that after shutdown() no new tasks are accepted and queued tasks finish.
submit(): hands a Runnable or a Callable to the pool and returns a Future at once.
Work queue: tasks wait here until a worker is free.
Worker threads: reused threads that each take the next task, run it and take another.
Rejection: a full bounded queue with every thread busy, or a pool after shutdown(), rejects new tasks with RejectedExecutionException by default.
Future: get() blocks until the task ends and returns its result, or throws ExecutionException with the task's exception as the cause.
shutdown(): refuses new tasks and lets queued and running ones finish.
A thread pool drawn from top to bottom. A caller box submits tasks into a work queue of four slots holding t4 to t7. A fifth task, t8, is marked rejected because the queue is full. Below, three worker threads run t1, t2 and t3, with an arrow from the queue into them. An arrow leads from the workers to a Future box, and a line carries the result from the Future back up to the caller. At the bottom, marks say that after shutdown() no new tasks are accepted and queued tasks finish.
submit(): hands a Runnable or a Callable to the pool and returns a Future at once.
Work queue: tasks wait here until a worker is free.
Worker threads: reused threads that each take the next task, run it and take another.
Rejection: a full bounded queue with every thread busy, or a pool after shutdown(), rejects new tasks with RejectedExecutionException by default.
Future: get() blocks until the task ends and returns its result, or throws ExecutionException with the task's exception as the cause.
shutdown(): refuses new tasks and lets queued and running ones finish.
Takeaway: submit() queues a task and returns a Future at once; a few reused worker threads take tasks from the queue, and the Future carries each result back.
In code
static int count; // shared by both threads
static final AtomicInteger atomic = new AtomicInteger();
// each of two threads runs this 1,000,000 times:
Wrong count++; // read, add, write: often ends below 2,000,000
Right atomic.incrementAndGet(); // one atomic step: always 2,000,000try (ExecutorService pool = Executors.newFixedThreadPool(3)) { // AutoCloseable since Java 19
Future<Integer> future = pool.submit(() -> 6 * 7); // returns at once
System.out.println(future.get()); // blocks until the task ends: 42
} // close(): shutdown, then waitclass Worker implements Runnable {
private volatile boolean running = true; // without volatile, the loop may never see false
public void run() { while (running) { /* poll a queue */ } }
void stop() { running = false; } // called from another thread
}Solve it
Transfer money between two accounts without a deadlock
transfer(from, to, amount) locks from, then to, then moves the money. Under load the service sometimes hangs:
one thread transfers A to B while another transfers B to A. Explain the hang and fix it.
- Trace the two threads. Thread 1 holds A and waits for B. Thread 2 holds B and waits for A. Neither can continue: a deadlock.
- Name the condition to break. A deadlock needs mutual exclusion, hold-and-wait, no preemption and a circular wait. Locking order is the easiest to control.
- Impose one global order. Always lock the account with the smaller id first, whichever way the money flows. A cycle can no longer form.
- Consider the alternative.
ReentrantLock.tryLockwith a timeout backs off and retries instead of waiting forever, at the cost of more code. - Check. Run thousands of opposite transfers on a thread pool: no hang, and the total balance never changes.
static void transfer(Account from, Account to, long amount) {
Right Account first = from.id() < to.id() ? from : to;
Right Account second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
from.withdraw(amount);
to.deposit(amount);
}
}
}How to answer
- synchronized gives mutual exclusion and visibility; volatile gives visibility and ordering only.
- count++ on a volatile int is still three steps, read, add and write, so two threads can overlap.
- A volatile boolean flag that one thread sets and others read is the classic correct use.
- Every object has a monitor; a synchronized method locks this, a static synchronized method locks the class.
Common mistakes
- Saying volatile makes count++ atomic; it only makes each read and write visible.
- Saying synchronized only matters for writes; a reader without the lock may see stale values.
Follow-up questions
What is the difference between Thread, Runnable and Callable?
A Thread is the object that runs code on a new thread of execution once you call start(). A Runnable is a task whose run() returns nothing and cannot throw a checked exception. A Callable is a task whose call() returns a value and may throw. You give a Runnable to a Thread, and either one to an ExecutorService, rather than subclassing Thread.
- Runnable: void run(). Callable<V>: V call() throws Exception.
- Submitting a Callable to an ExecutorService returns a Future that carries its result or its exception.
- Passing a task to a Thread or a pool separates what runs from how it runs.
Runnable log = () -> System.out.println("hi");
Callable<Integer> answer = () -> 42;
new Thread(log).start();
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Integer> future = pool.submit(answer);
System.out.println(future.get()); // 42
} What is a race condition?
A race condition is a bug whose outcome depends on how threads happen to interleave. It needs shared mutable state and at least one unsynchronized write. With count++, two threads can both read 0 and both write 1, so the count ends lower than the number of increments. Fix it with synchronized, a Lock or an atomic class, or avoid sharing the state.
- The result changes from run to run, which makes a race hard to reproduce.
- Check-then-act, such as if (!map.containsKey(k)) map.put(k, v), is a race too.
- Two threads doing 1,000,000 unsynchronized count++ each often end below 2,000,000.
static int count;
Runnable task = () -> {
for (int i = 0; i < 1_000_000; i++) count++;
};
// two threads run task: count often ends below 2,000,000 What is a deadlock and how do you prevent it?
A deadlock is two or more threads each holding a lock and waiting for a lock another of them holds, so none can continue. Thread 1 holds A and waits for B while thread 2 holds B and waits for A. The usual prevention is one global lock order: every thread takes A before B, so the wait can never form a cycle.
- A deadlock needs a cycle of threads each waiting for a lock the next one holds.
- Take locks in one fixed order, hold as few as possible, and never call unknown code while holding one.
- ReentrantLock.tryLock() with a timeout lets a thread give up instead of waiting forever.
- jstack or ThreadMXBean.findDeadlockedThreads() reports the threads that are stuck.
See it in the infographic: How a deadlock forms, and the fix
What is an ExecutorService and why use one?
An ExecutorService runs submitted tasks on a pool of reused worker threads. submit() puts a Runnable or Callable in a work queue and returns a Future at once; a free worker takes the task, and future.get() waits for its result. Reusing threads avoids the cost of one thread per task and caps how many run at once. Shut the pool down when you are done.
- Executors.newFixedThreadPool(n) keeps n workers over an unbounded queue.
- future.get() blocks; if the task threw, it throws ExecutionException with the task's exception as the cause.
- shutdown() refuses new tasks and lets queued ones finish; shutdownNow() interrupts running ones.
- Since Java 19 an ExecutorService is AutoCloseable, so try-with-resources shuts it down and waits.
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
Future<Integer> future = pool.submit(() -> 6 * 7);
System.out.println(future.get()); // 42
} // close(): shutdown(), then wait for the tasks What is the difference between calling start() and run() on a Thread?
start() creates a new thread, which then calls run(). Calling run() yourself is an ordinary method call: the code runs on the current thread, so nothing happens in parallel. Calling start() a second time on the same Thread throws IllegalThreadStateException.
- Inside run() called directly, Thread.currentThread().getName() is the caller's thread, for example main.
- A Thread can be started only once; create a new Thread or use a pool to run the task again.
Thread worker = new Thread(
() -> System.out.println(Thread.currentThread().getName()), "worker");
worker.run(); // prints main
worker.start(); // prints worker
worker.start(); // IllegalThreadStateException What does happens-before mean in the Java Memory Model?
If one action happens-before another, the second sees the effects of the first. Unlocking a monitor happens-before every later lock of it, a volatile write happens-before every later read of that variable, Thread.start() happens-before the started thread's actions, and a thread's actions happen-before another thread returns from join() on it. Without such an edge, a thread may read a stale value.
Is count++ atomic?
No. It compiles to a read of count, an add and a write back, and another thread can run between those steps. Two threads that both read 0 both write 1, and one update is lost. Making count volatile does not help; use synchronized, a Lock or AtomicInteger.incrementAndGet().
When would you use AtomicInteger instead of synchronized?
For one variable updated on its own, such as a counter. AtomicInteger uses a hardware compare-and-set instead of a lock, so threads never block on it. When several variables must change together, for example a balance and its history, you need synchronized or a Lock around the whole update.
Check yourself
Show answers
- 1 or 2: Correct. If both threads read 0 before either writes, both write 1 and one update is lost.
- Only 2: Incorrect. count++ is a read, an add and a write, and the two threads can interleave between them.
- 0, 1 or 2: Incorrect. Each thread writes the value it read plus one, so the last write is at least 1.
Show answers
- Make both threads lock A before B: Correct. With one lock order, a thread holding A never waits for a thread holding B, so no cycle forms.
- Declare the lock fields volatile: Incorrect. volatile changes visibility of the fields, not the order in which the threads take the locks.
- Call Thread.sleep() between the two locks: Incorrect. Sleeping while holding the first lock only makes the other thread more likely to take its first lock.
Show answers
- Throws ExecutionException with the IllegalStateException as its cause: Correct. The Future stores the task's exception and wraps it when get() is called.
- Throws the IllegalStateException itself: Incorrect. get() always wraps a task's exception in ExecutionException.
- Returns null: Incorrect. A task that threw has no result, so get() throws instead of returning.