synchronized, volatile and Race Conditions
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)"Two threads increment one counter. What goes wrong, and how do you fix it?" is the most common concurrency question. The interviewer is checking that you can name the bug, then pick the right tool: synchronized, volatile or an atomic class.
Race condition: counter++ is not atomic
Race condition is a bug where the result depends on the timing of threads that use shared data. An operation is atomic when no other thread can see it half done.
count++ looks like one step, but it is read, add one, write back. This program runs two threads that each add 100,000 likes and shows that updates are lost.
Example 1 · Lost updates: two threads, one counter
public class RaceDemo { static int likes = 0;
public static void main(String[] args) throws InterruptedException { Runnable tap = () -> { for (int i = 0; i < 100_000; i++) { likes++; // read, add 1, write: three steps } }; Thread a = new Thread(tap); Thread b = new Thread(tap); a.start(); b.start(); a.join(); b.join(); System.out.println("Expected 200000, got " + likes); }}Expected 200000, got 131248
What this code does
- Each thread adds 100000, so the answer should be 200000. Because
likes++is read-add-write, increments overlap and get lost; the number changes on every run. - This is a race condition: the result depends on timing. Your number will differ, and on some runs it may even be correct, which is why such bugs are hard to catch in testing.
Two threads can both read 41, both add 1 and both write 42, so one increment is lost. Model answer, spoken: "A race condition is when correctness depends on thread timing. count++ is read-modify-write, so updates get lost. I fix it by making the whole operation atomic with a lock or an atomic class."
Spot a race with this checklist:
- Shared + mutable + at least one writer + no synchronization = race.
- Read-modify-write:
count++,balance = balance + x. - Check-then-act:
if (seats > 0) seats--;, lazy initialisation. - The bug is intermittent: tests may pass many times, then fail.
Find the bug
Spot the race
Click the line that is not thread-safe.
Many threads call increment(). Which line loses updates?
Round 1 of 2synchronized: methods vs blocks, object lock vs class lock
Monitor lock is the lock every Java object has. A synchronized block takes it, so only one thread at a time can run code guarded by the same lock; others wait in the BLOCKED state.
Two fixes follow: a synchronized method and a synchronized block. Then Thread.holdsLock shows which lock an instance method, a static method and a block take.
Example 2 · Fix with a synchronized method or a synchronized block
class LikeCounter { private int likes = 0; private final Object lock = new Object();
synchronized void tapMethod() { // locks on this likes++; }
void tapBlock() { synchronized (lock) { // locks only this block likes++; } }
synchronized int get() { return likes; }}
public class SyncFixDemo { public static void main(String[] args) throws InterruptedException { LikeCounter c1 = new LikeCounter(); Thread a = new Thread(() -> { for (int i = 0; i < 100_000; i++) c1.tapMethod(); }); Thread b = new Thread(() -> { for (int i = 0; i < 100_000; i++) c1.tapMethod(); }); a.start(); b.start(); a.join(); b.join(); System.out.println("synchronized method: " + c1.get());
LikeCounter c2 = new LikeCounter(); Thread c = new Thread(() -> { for (int i = 0; i < 100_000; i++) c2.tapBlock(); }); Thread d = new Thread(() -> { for (int i = 0; i < 100_000; i++) c2.tapBlock(); }); c.start(); d.start(); c.join(); d.join(); System.out.println("synchronized block: " + c2.get()); }}synchronized method: 200000 synchronized block: 200000
What this code does
synchronized void tapMethod()locksthis, so only one thread at a time runslikes++: the total is always 200000.tapBlocklocks a privatelockobject for just the increment; the result is the same.get()is also synchronized somainsees the final value.
Example 3 · Object lock vs class lock
class Hostel { static int totalRooms = 0; int rooms = 0;
synchronized void addRoom() { // object lock: this rooms++; System.out.println("instance method holds this lock? " + Thread.holdsLock(this) + ", class lock? " + Thread.holdsLock(Hostel.class)); }
static synchronized void addToTotal() { // class lock: Hostel.class totalRooms++; System.out.println("static method holds class lock? " + Thread.holdsLock(Hostel.class)); }}
public class ObjectVsClassLockDemo { public static void main(String[] args) { Hostel ganga = new Hostel(); Hostel yamuna = new Hostel(); ganga.addRoom(); Hostel.addToTotal(); synchronized (ganga) { System.out.println("main holds ganga's lock? " + Thread.holdsLock(ganga) + ", yamuna's lock? " + Thread.holdsLock(yamuna)); } }}instance method holds this lock? true, class lock? false static method holds class lock? true main holds ganga's lock? true, yamuna's lock? false
What this code does
Thread.holdsLockshows which monitor the current thread owns: the instance method holdsthisbut notHostel.class; thestatic synchronizedmethod holdsHostel.class.- Holding
ganga's lock says nothing aboutyamuna's: each object has its own monitor, so threads working on different objects never block each other.
A synchronized instance method locks this; a static synchronized method locks the Class object; a synchronized (obj) block locks whatever you name. Leaving the block, even through an exception, releases the lock. An instance lock and the class lock are independent, and threads using different objects do not block each other.
Prefer a block when only part of a method touches shared data, with a private final Object lock so outside code cannot take your lock. synchronized is reentrant, and it gives mutual exclusion and visibility. Never lock on a String literal or a boxed Integer, and synchronize reads too.
volatile: visibility, not atomicity
volatile is a Java keyword for a variable that guarantees visibility. Every read sees the latest write by any thread, but compound actions such as count++ are still not atomic.
A thread can keep a variable in a CPU cache and never see another thread's write. This program shows a volatile stop flag that works, and a volatile counter that still loses updates.
Example 4 · volatile fixes visibility but not ++
public class VolatileFlagDemo { static volatile boolean running = true; // remove volatile and the loop may never stop static volatile int counter = 0;
public static void main(String[] args) throws InterruptedException { Thread worker = new Thread(() -> { long loops = 0; while (running) { loops++; } System.out.println("worker saw running = false and stopped"); }); worker.start(); Thread.sleep(100); running = false; // this write becomes visible to worker worker.join();
Runnable add = () -> { for (int i = 0; i < 100_000; i++) { counter++; // volatile, but still not atomic } }; Thread a = new Thread(add); Thread b = new Thread(add); a.start(); b.start(); a.join(); b.join(); System.out.println("volatile counter (expected 200000): " + counter); }}worker saw running = false and stopped volatile counter (expected 200000): 166704
What this code does
- The
volatileflag guarantees the worker seesrunning = false, so the loop ends. Withoutvolatilethe JIT may hoist the read out of the loop and the thread can spin forever. - The
volatile int counterstill loses updates, becausecounter++is not atomic: the second line changes from run to run. Visibility is not atomicity.
Writes before a volatile write become visible to a thread that later reads it (a happens-before relationship). volatile does not make count++ atomic, because read, add and write are still three steps.
Use volatile for a single variable written by one thread and read by others, such as a stop flag or a published reference. Use synchronized or an atomic class whenever the new value depends on the old one.
AtomicInteger and compare-and-set
CAS (compare-and-set) changes a variable only if it still holds the expected value, in one atomic step, and returns whether it worked. Atomic classes retry it until it succeeds.
AtomicInteger gives atomic updates without locks. This program counts likes from two threads and books the last seat with compareAndSet.
Example 5 · AtomicInteger, AtomicLong and compareAndSet
import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;
public class AtomicDemo { public static void main(String[] args) throws InterruptedException { AtomicInteger likes = new AtomicInteger(); AtomicLong collected = new AtomicLong();
Runnable tap = () -> { for (int i = 0; i < 100_000; i++) { likes.incrementAndGet(); collected.addAndGet(2); } }; Thread a = new Thread(tap); Thread b = new Thread(tap); a.start(); b.start(); a.join(); b.join(); System.out.println("likes = " + likes.get()); System.out.println("collected = " + collected.get());
AtomicInteger seats = new AtomicInteger(1); boolean first = seats.compareAndSet(1, 0); // book the last seat boolean second = seats.compareAndSet(1, 0); // already taken System.out.println("first booking: " + first + ", second booking: " + second); }}likes = 200000 collected = 400000 first booking: true, second booking: false
What this code does
incrementAndGetandaddAndGetare atomic, so no update is lost and both totals are exact, with nosynchronizedat all.compareAndSet(1, 0)books the last seat only if it is still 1. The first call succeeds; the second finds 0 and returnsfalse, so the seat is never booked twice.
AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference offer incrementAndGet(), addAndGet(n), getAndIncrement() and updateAndGet(f). Use atomics for a single counter or flag; when several variables must change together, use a lock.
Under very heavy contention, LongAdder is faster than AtomicLong for counters, because it spreads updates over several cells.
Predict the output
Predict the atomic result
Read the code, then pick what it prints.
Round 1 of 2
Two compareAndSet calls in a row.
wait/notify and the producer-consumer question
Producer-consumer is a pattern where one thread adds items to a shared buffer and another removes them. The producer waits when the buffer is full, and the consumer waits when it is empty.
With wait and notifyAll, both methods are synchronized on the buffer and wait in a while loop. This program passes four orders through a one-item mailbox.
Example 6 · Producer-consumer with wait and notifyAll
class Mailbox { private Integer item; // null means empty
synchronized void put(int value) throws InterruptedException { while (item != null) { wait(); // wait until the consumer empties it } item = value; System.out.println("produced order " + value); notifyAll(); }
synchronized int take() throws InterruptedException { while (item == null) { wait(); // wait until the producer fills it } int value = item; item = null; System.out.println("consumed order " + value); notifyAll(); return value; }}
public class ProducerConsumerDemo { public static void main(String[] args) throws InterruptedException { Mailbox box = new Mailbox(); Thread seller = new Thread(() -> { try { for (int i = 1; i <= 4; i++) box.put(i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); Thread packer = new Thread(() -> { try { for (int i = 1; i <= 4; i++) box.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); seller.start(); packer.start(); seller.join(); packer.join(); System.out.println("all orders served"); }}produced order 1 consumed order 1 produced order 2 consumed order 2 produced order 3 consumed order 3 produced order 4 consumed order 4 all orders served
What this code does
- The mailbox holds one order.
putwaits while it is full andtakewaits while it is empty, each in awhileloop, and each callsnotifyAll()after changing it. - Because the prints happen inside the synchronized methods and the box holds one item, the order is always produced 1, consumed 1, produced 2, and so on.
Each method waits in a while loop on its condition and calls notifyAll() after changing the buffer. Model answer: "I call wait() in a while loop, not an if, because a thread can wake up while the condition is still false. I prefer notifyAll so the right thread is not missed."
In real code use a BlockingQueue such as ArrayBlockingQueue: its put waits when full and its take waits when empty, so you write none of this by hand.
Order of execution
Order the consumer's steps
Put the consumer's take() steps in the right order.
Next step
Check your understanding
12 quick questions