In part 1 we started threads, waited for them with join(), and stopped them politely with interrupt(). Nothing went wrong, because no two threads ever wrote to the same data.
This article is about what happens when they do. Every bug here is real: I ran each one on my machine, and the output below is copied from those runs.
| # | Lesson |
|---|---|
| 1 | Multithreading basics |
| 2 | Synchronization (this article) |
| 3 | ExecutorService |
| 4 | CompletableFuture |
| 5 | Concurrent collections |
| 6 | Virtual threads |
| 7 | Capstone: a coffee shop that uses all of it |
Code: github.com/baarayy/advanced-java-section · Run this lesson with ./mvnw -q compile exec:java -Dexec.args=2
Two kinds of bugs
Threads share the heap: every object and field is visible to all of them. When several threads read and write the same field, two different things can go wrong:
- Atomicity. An operation that looks like one step is really several, and another thread can sneak in between them. Updates get lost.
- Visibility. A thread keeps using an old value (in a CPU register or cache) and never sees what another thread wrote.
Synchronization fixes both. Let's break things first.
1. The race condition: 1.7 million lost tips
Four baristas share one tip jar. Each drops in 1,000,000 tips with tips++:
Almost half the tips are gone. Run it again and you get a different number: in the run I quoted at the end of part 1 it was 2,454,514. The result changes every time, which is the signature of a race condition.
Why tips++ loses updates
tips++ is one line of Java, but the CPU does three separate steps: read the value, add 1, write it back. Two threads can interleave them like this:
| Step | barista-1 | barista-2 | tips in memory |
|---|---|---|---|
| 1 | reads 41 | 41 | |
| 2 | reads 41 | 41 | |
| 3 | adds 1 → 42 | 41 | |
| 4 | adds 1 → 42 | 41 | |
| 5 | writes 42 | 42 | |
| 6 | writes 42 | 42 |
Two tips went in, and the jar went up by one. Repeat that millions of times across four threads and you lose millions of tips.
Two details that made the bug show up reliably
The volatile is there on purpose, to prove it doesn't help. volatile makes every read and write go to main memory, but read, add, write is still three separate steps. A lot of people believe volatile makes ++ safe. It doesn't.
(There's a second reason. Without volatile, the JIT compiler can turn the whole loop into a single write at the end, and on some runs the race hides. A bug that hides on some runs is the worst kind, because your tests pass.)
The threads start together. If you just start four threads in a loop, the first one may finish its million tips before the last one even starts, and they never overlap. So each barista waits at a CountDownLatch, and main opens the gate once all four are ready:
Keep that in mind when you write concurrency tests: if your threads never actually overlap, your test proves nothing.
2. Fix #1: synchronized
Every Java object has a built-in lock, called its monitor. A synchronized method takes the monitor of this before running and releases it after. Only one thread can hold it, so only one barista can be inside addTip() at a time, and the three steps of tips++ can't interleave anymore.
Notice that total() is synchronized too, even though it only reads. Releasing a lock publishes everything the thread wrote; taking the same lock guarantees you see it. A reader that skips the lock has no such guarantee. Java calls this the happens-before rule: everything before an unlock is visible to whoever takes the same lock next.
You can also lock a block instead of a whole method, which keeps the locked region small:
3. Fix #2: ReentrantLock
Same guarantee as synchronized, more control. The main extra is tryLock: try to get the lock, but give up after a timeout instead of waiting forever.
Use ReentrantLock when you need tryLock, a timeout, an interruptible wait, fairness, or several wait conditions. Otherwise synchronized is simpler and can't be left locked by a forgotten unlock().
"Reentrant" means the thread holding the lock can take it again without deadlocking itself.
synchronizedis reentrant too.
4. Fix #3: atomics, with no lock at all
AtomicInteger uses a CPU instruction called compare-and-swap (CAS): "set the value to 42, but only if it's still 41". If another thread changed it in between, the swap fails and the thread simply retries with the new value. Nobody waits for a lock.
LongAdder goes further for counters with many writers: each thread adds to its own cell, and sum() adds the cells up when you read. It was the fastest of the four in this run.
| Fix | Time in this run | Best for |
|---|---|---|
synchronized | 234 ms | Several fields that must change together; the simple default |
ReentrantLock | 85 ms | The same, when you need tryLock, timeouts or fairness |
AtomicInteger | 85 ms | One variable |
LongAdder | 43 ms | A counter with many writers and rare reads (metrics) |
Don't read too much into the exact numbers: they move between runs and machines. The rule that holds is that atomics are perfect for one variable. As soon as two values have to change together, you need a lock. We'll see exactly that in the capstone (lesson 7).
5. Check-then-act: selling the last croissant twice
Races aren't only about counters. One croissant left, two customers:
Both customers checked, both saw 1, both bought. The check and the act are each fine on their own; the gap between them is the bug. It's the same pattern as "if the file doesn't exist, create it" or "if the username is free, register it".
The fix is to put the check and the act under the same lock, so they become one atomic step:
The 50 ms hesitation is inside the lock only to keep the demo short. In real code, keep locked sections as small as you can (see the common mistakes below).
6. Visibility: the loop that never ends
The second kind of bug. The cashier spins until the shop closes:
With volatile it works. Then I removed volatile and ran it three times. The cashier never stopped, all three times. I had to kill the process.
What happened: the JIT compiler saw a loop that reads open but never writes it, and decided it could read the field once and keep the value in a register. From then on, main's write to open was invisible to the cashier. The code is "correct" Java, and it hangs forever.
volatile forbids that optimization: every read goes to memory and sees the latest write. It's the right tool for a flag written by one thread and read by others. It's the wrong tool for tips++ (section 1), because it doesn't make anything atomic.
7. Deadlock
Two baristas each need the grinder and the milk steamer. One grabs the grinder first, the other grabs the steamer first:
A holds the grinder and waits for the steamer. B holds the steamer and waits for the grinder. Neither will ever let go. To keep the demo from hanging, the lesson runs them as daemon threads and asks the JVM's own deadlock detector what it sees:
This is the same report jstack <pid> prints for a hung production app, so it's worth recognizing.
The fix: always lock in the same order
A deadlock needs a cycle: A waits for B, and B waits for A. If every thread takes the locks in the same order (grinder first, then steamer, always), no cycle can form:
The other common fix is tryLock with a timeout (section 3): if you can't get the second lock in time, release the first and try again later.
Which tool when?
| You need to... | Use |
|---|---|
| Protect several fields that change together | synchronized |
The same, with a timeout or tryLock | ReentrantLock (unlock in finally) |
| Update one counter or reference | AtomicInteger, AtomicLong, AtomicReference |
| Count events from many threads | LongAdder |
| Signal a stop flag to another thread | volatile boolean |
| Take several locks | The same global order, everywhere |
Common mistakes
- Synchronizing the writes but not the reads. Readers can see stale values.
- Two synchronized calls in a row (check, then act). Each call is safe; the pair isn't.
- Different locks for the same data. The lock must be the same object for every thread.
- Doing slow I/O while holding a lock. Everyone else waits for your network call.
- Believing
volatilemakes++safe. It gives visibility, not atomicity.
Try it yourself
- Remove
volatilefromShop.openand run lesson 2. Does the cashier ever stop on your machine? - Change
buySafeto synchronize only thecroissants--line. Is it still safe? Why not? - Make both baristas in
deadlock()take the grinder first. What does the detector report now? - Time
SynchronizedTipJaragainstAtomicTipJarwith 8 threads instead of 4.
Next: ExecutorService
So far we've created every thread by hand, one per task. That doesn't scale: platform threads are expensive, and nothing stops you from creating ten thousand of them. In part 3 we hand the work to a pool: three baristas working through a line of orders, with Futures to get results back, timeouts, scheduled tasks, and the exception-swallowing gotcha that hides bugs in a lot of real code.
Source code: github.com/baarayy/advanced-java-section · This lesson: Lesson2Synchronization.java

