Albaraa Ahmed/ Writing
Portfolio
JavaSynchronizationMultithreading

Java Concurrency, Hands-On #2: Synchronization

Dec 3, 20267 min read
Part 2 of 2 · Java Concurrency
  1. Java Concurrency, Hands-On #1: Multithreading Basics
  2. Java Concurrency, Hands-On #2: Synchronization

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
1Multithreading basics
2Synchronization (this article)
3ExecutorService
4CompletableFuture
5Concurrent collections
6Virtual threads
7Capstone: 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:

  1. Atomicity. An operation that looks like one step is really several, and another thread can sneak in between them. Updates get lost.
  2. 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++:

Lesson2Synchronization.javajava
static final class UnsafeTipJar implements TipJar {
    private volatile int tips;
    public void addTip() { tips++; }
    public long total() { return tips; }
}
[  118 ms] [main] volatile int tips++  expected 4,000,000  got 2,248,518  WRONG, lost 1,751,482 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:

Stepbarista-1barista-2tips in memory
1reads 4141
2reads 4141
3adds 1 → 4241
4adds 1 → 4241
5writes 4242
6writes 4242

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:

Lesson2Synchronization.javajava
CountDownLatch startGate = new CountDownLatch(1);
for (int i = 1; i <= BARISTAS; i++) {
    baristas.add(Thread.ofPlatform().name("barista-" + i).start(() -> {
        startGate.await();               // wait here until the gate opens (try/catch omitted)
        for (int t = 0; t < TIPS_EACH; t++) {
            jar.addTip();
        }
    }));
}
startGate.countDown();                   // open the gate: everyone starts at once

Keep that in mind when you write concurrency tests: if your threads never actually overlap, your test proves nothing.

2. Fix #1: synchronized

Lesson2Synchronization.javajava
static final class SynchronizedTipJar implements TipJar {
    private int tips;
    public synchronized void addTip() { tips++; }
    public synchronized long total() { return tips; }
}
[  356 ms] [main] synchronized         expected 4,000,000  got 4,000,000  OK  (234 ms)

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:

java
synchronized (this) {
    tips++;
}

3. Fix #2: ReentrantLock

Lesson2Synchronization.javajava
static final class LockedTipJar implements TipJar {
    private final ReentrantLock lock = new ReentrantLock();
    private int tips;

    public void addTip() {
        lock.lock();
        try {
            tips++;
        } finally {
            lock.unlock(); // ALWAYS unlock in finally, or an exception leaves it locked forever
        }
    }
}
[  442 ms] [main] ReentrantLock        expected 4,000,000  got 4,000,000  OK  (85 ms)

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.

Lesson2Synchronization.javajava
if (espressoMachine.tryLock(100, TimeUnit.MILLISECONDS)) {
    try {
        log("Got the machine");
    } finally {
        espressoMachine.unlock();
    }
} else {
    log("Machine busy for more than 100 ms, serving a cold brew instead (tryLock timed out)");
}
[  595 ms] [main] Machine busy for more than 100 ms, serving a cold brew instead (tryLock timed out)

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. synchronized is reentrant too.

4. Fix #3: atomics, with no lock at all

Lesson2Synchronization.javajava
static final class AtomicTipJar implements TipJar {
    private final AtomicInteger tips = new AtomicInteger();
    public void addTip() { tips.incrementAndGet(); }
    public long total() { return tips.get(); }
}
[ 1030 ms] [main] AtomicInteger        expected 4,000,000  got 4,000,000  OK  (85 ms)
[ 1079 ms] [main] LongAdder            expected 4,000,000  got 4,000,000  OK  (43 ms)

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.

FixTime in this runBest for
synchronized234 msSeveral fields that must change together; the simple default
ReentrantLock85 msThe same, when you need tryLock, timeouts or fairness
AtomicInteger85 msOne variable
LongAdder43 msA 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:

Lesson2Synchronization.javajava
boolean buyUnsafe() {
    if (croissants > 0) {        // check
        Work.io(50);             // ...the customer hesitates...
        croissants--;            // act
        return true;
    }
    return false;
}
[ 1132 ms] [customer-Mona] Got the croissant!
[ 1132 ms] [customer-Ali ] Got the croissant!
[ 1133 ms] [main         ] Unsafe: croissants left = -1   (negative: we sold one we didn't have!)

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:

Lesson2Synchronization.javajava
synchronized boolean buySafe() {
    if (croissants > 0) {
        Work.io(50);
        croissants--;
        return true;
    }
    return false;
}

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).

[ 1184 ms] [customer-Mona] Sold out
[ 1184 ms] [customer-Ali ] Got the croissant!
[ 1184 ms] [main         ] Safe:   croissants left = 0

6. Visibility: the loop that never ends

The second kind of bug. The cashier spins until the shop closes:

Lesson2Synchronization.javajava
static final class Shop {
    private volatile boolean open = true;
    void close() { open = false; }
    boolean isOpen() { return open; }
}

// cashier thread
while (shop.isOpen()) {
    spins++;
}
[ 1286 ms] [main   ] Closing the shop
[ 1286 ms] [cashier] Saw the shop close after 310,749,052 loop iterations

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:

Lesson2Synchronization.javajava
// barista-A
synchronized (grinder) {
    Work.io(100);
    synchronized (steamer) { /* make latte */ }
}

// barista-B
synchronized (steamer) {
    Work.io(100);
    synchronized (grinder) { /* make latte */ }
}

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:

Lesson2Synchronization.javajava
ThreadMXBean jvm = ManagementFactory.getThreadMXBean();
long[] stuck = jvm.findDeadlockedThreads();
[ 1288 ms] [barista-A] Holding the GRINDER, waiting for the steamer...
[ 1289 ms] [barista-B] Holding the STEAMER, waiting for the grinder...
[ 1818 ms] [main     ] The JVM detected a deadlock between 2 threads:
   barista-A is BLOCKED, waiting for a lock held by barista-B
   barista-B is BLOCKED, waiting for a lock held by barista-A

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:

Lesson2Synchronization.javajava
Runnable makeLatte = () -> {
    synchronized (grinder) {      // 1st: grinder, for everyone
        Work.io(100);
        synchronized (steamer) {  // 2nd: steamer, for everyone
            log("Got the grinder and the steamer, latte done");
        }
    }
};
[ 1921 ms] [barista-A] Got the grinder and the steamer, latte done
[ 2022 ms] [barista-B] Got the grinder and the steamer, latte done

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 togethersynchronized
The same, with a timeout or tryLockReentrantLock (unlock in finally)
Update one counter or referenceAtomicInteger, AtomicLong, AtomicReference
Count events from many threadsLongAdder
Signal a stop flag to another threadvolatile boolean
Take several locksThe 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 volatile makes ++ safe. It gives visibility, not atomicity.

Try it yourself

  1. Remove volatile from Shop.open and run lesson 2. Does the cashier ever stop on your machine?
  2. Change buySafe to synchronize only the croissants-- line. Is it still safe? Why not?
  3. Make both baristas in deadlock() take the grinder first. What does the detector report now?
  4. Time SynchronizedTipJar against AtomicTipJar with 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

Keep reading