Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 201 ยท Concurrency

Synchronization and Race Conditions

Understand race conditions in Java and fix them with synchronized methods and blocks, intrinsic locks, volatile and the happens-before rules, with runnable demos.

When two threads read and write the same variable, the result can depend on the exact timing of their steps. That's a race condition, and it's the classic concurrency bug: code that looks obviously correct, passes every test on your laptop, and then loses money or corrupts data in production once a week.

This lesson shows races happening for real, then fixes them with Java's built-in tool, the synchronized keyword. You'll also meet the second, sneakier problem of shared memory, visibility, and the volatile keyword and happens-before rules that solve it. It builds on Threads and Thread Lifecycle and Priorities.

A race condition you can watch

Four threads each add 1 to a shared counter 100,000 times. The answer should obviously be 400,000:

Java Lost updates with count++

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Most runs print a smaller number, and a different one each time. (Now and then a run happens to come out right, which is what makes races so hard to catch in testing.) The reason: count++ looks like one operation but is really three:

  1. read count from memory into a register,
  2. add 1,
  3. write the result back.

If two threads interleave those steps, one update vanishes:

TEXT
Thread A                 Thread B                 count in memory
read count  (41)                                   41
                         read count  (41)          41
add 1       (42)                                   41
                         add 1       (42)          41
write 42                                           42
                         write 42                  42   โ† one increment lost

The same pattern appears whenever code does read-modify-write (x++, x += n, list.add on an ArrayList) or check-then-act (if (!map.containsKey(k)) map.put(k, v)) on shared data. The section of code that touches the shared state is called the critical section, and the fix is to make sure only one thread at a time can be inside it.

synchronized methods

Every Java object has a built-in lock, called its intrinsic lock or monitor. A synchronized method acquires the lock of this before it runs and releases it when it returns, even if it throws. While one thread holds the lock, any other thread trying to enter a synchronized method on the same object waits in the BLOCKED state.

Java Fixing the counter with synchronized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Now the answer is 400,000 every time. Notice that get() is synchronized too. That isn't about atomicity (reading an int is already one step); it's about visibility, explained below. A good rule: if a field is protected by a lock, every access to it, reads and writes, uses that lock.

Synchronization has a cost: threads queue up for the lock instead of running in parallel. Keep critical sections short, and never do slow work like I/O or sleeping while holding a lock. For a simple counter, AtomicInteger or LongAdder is faster still (Atomic Variables).

synchronized blocks and lock objects

A synchronized block locks any object you name, and only for the lines inside it:

Java
synchronized (someObject) {
    // only one thread at a time holds someObject's lock here
}

Blocks give you two advantages: you can keep the locked region smaller than a whole method, and you can choose which lock to use. Many developers prefer a private final lock object over this, because outside code can also lock on your object (synchronized (yourObject)) and accidentally interfere, while nobody else can reach a private field.

This example also shows a check-then-act race. Two threads withdraw from the same account; the balance check and the withdrawal must happen as one unit, or both threads can pass the check before either subtracts:

Java Check-then-act: an overdrawn account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The unsafe version lets both ATMs withdraw 80 from a balance of 100, leaving -60. The sleep only makes the window wide enough to hit every time; without it, the same bug still happens, just rarely. The safe version always refuses one of them (which ATM wins varies from run to run). Holding a lock across sleep is bad practice in real code; here it stands in for a slow step to make the point visible.

Which lock does each form use?

Code Lock used
synchronized void m() this
static synchronized void m() the Class object (Account.class)
synchronized (obj) { ... } obj

Synchronization only works if all threads use the same lock for the same data. A static synchronized method and an instance synchronized method use different locks, so they don't exclude each other. And synchronized (new Object()) locks a brand-new object that no other thread can see: it protects nothing.

Don't lock on strings, boxed numbers or other shared values (synchronized ("lock") or on an Integer). String literals and small Integer values are shared across the whole JVM, so unrelated code may lock the same object. Never lock on a field you reassign, either: after lock = new Object(), threads use different locks.

Static synchronization: the class lock

A static synchronized method locks the Class object, and there is only one Class object per class in a JVM. So it protects static data and makes all threads wait on one lock, no matter how many instances exist. An instance synchronized method locks this, so two threads using two different instances don't block each other. This is called object-level versus class-level locking. Working through the combinations for a class with a static synchronized method s1(), another static synchronized method s2() and an instance synchronized method i1():

Thread A runs Thread B runs Do they exclude each other?
s1() s2() Yes: both need the Account.class lock
s1() i1() on any object No: Account.class and the object are different locks
i1() on a i1() on the same a Yes: same object lock
i1() on a i1() on another object b No: different object locks
Java Class lock versus object lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first half proves the static counter is exact even though each thread uses its own Counter. In the second half, B finishes (the object lock was free) while A still holds the class lock, so the "B releases" line prints before "A releases". Choose the lock by what the data belongs to: static fields need a static lock, instance fields an instance lock.

Reentrancy

Intrinsic locks are reentrant: a thread that already holds a lock can acquire it again without blocking itself. So a synchronized method can call another synchronized method on the same object, and a subclass's synchronized method can call super's:

Java Intrinsic locks are reentrant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without reentrancy, addAll would deadlock on itself. Thread.holdsLock(obj) is handy in assertions and tests.

Visibility: the other half of the problem

Races aren't the only danger. For speed, the CPU and the JIT compiler may keep a value in a register or core-local cache, and reorder reads and writes, as long as the current thread can't tell. Another thread, however, may see stale values, or see writes in a surprising order. Without synchronization, there's no guarantee that one thread ever sees another thread's write.

The classic example is a stop flag:

Java
class Worker extends Thread {
    private boolean running = true;         // not volatile: BROKEN

    public void run() {
        while (running) {                   // the JIT may read 'running' once and loop forever
            // work
        }
    }

    public void shutdown() {
        running = false;                    // written by another thread
    }
}

On a typical desktop JVM, the optimizing compiler sees that the loop body never changes running, hoists the read out of the loop, and the worker never stops, even long after shutdown() was called. (Our online editor runs Java with a simpler compiler and a single core, so the hang may not show up there. That's exactly the trouble with these bugs: they depend on the machine.)

The fix is to declare the field volatile. Every read of a volatile field sees the latest write by any thread, and the compiler can't cache or hoist it:

Java A volatile stop flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For stopping threads, interrupts are usually better than your own flag, because they also wake a thread that's sleeping or waiting. A volatile flag is still a common, valid pattern for loops that never block.

volatile is not atomic

volatile fixes visibility, not race conditions. count++ on a volatile field is still read, add, write, and still loses updates:

Java volatile does not make ++ safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Use volatile when one thread writes a value and others read it (flags, a published configuration object, a "latest price"), or when each write doesn't depend on the old value. For read-modify-write, use a lock or an atomic class.

Happens-before, simply

The Java Memory Model defines when a write by one thread is guaranteed to be visible to a read by another. The rule is called happens-before: if action A happens-before action B, then B sees A's effects (and everything A's thread did before A). The everyday rules:

  • Program order: within one thread, each statement happens-before the next.
  • Locks: unlocking a monitor happens-before every later locking of the same monitor. Everything a thread did inside (and before) a synchronized block is visible to the next thread that enters a block on the same lock.
  • volatile: a write to a volatile field happens-before every later read of that field.
  • Thread start: everything before t.start() is visible to the code in t.
  • Thread end: everything thread t did is visible to a thread that returns from t.join().
  • Transitivity: if A happens-before B and B happens-before C, then A happens-before C.

That's why the parallel sum in Threads was correct without locks: join() made each worker's result visible. It's also why Counter.get() above had to be synchronized: without it, no rule connects the incrementing threads' writes to the reading thread.

The java.util.concurrent classes document their own guarantees in the same terms. For example, putting an object into a ConcurrentHashMap or a BlockingQueue happens-before another thread retrieving it.

Safer designs

Locks are the last resort, not the first. Ways to need fewer of them:

  • Don't share. Give each thread its own data and combine results at the end, as in the parallel sum.
  • Share only immutable objects. An immutable object (final fields, no setters) can be read by any number of threads with no synchronization. Records with immutable components are perfect.
  • Use thread-safe classes from java.util.concurrent: ConcurrentHashMap, AtomicInteger, BlockingQueue (Concurrent Collections).
  • Confine mutable state to one thread and send it messages through a queue.

Collections.synchronizedList(list) wraps every method in a lock, but compound actions such as "check then add" and iteration still need your own synchronized (list) { ... } block around them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can count++ on a shared int lose updates when several threads run it?

    The three steps can interleave between threads, so one increment overwrites another. A lock or an atomic class makes the whole read-modify-write one indivisible step.
  2. 2. Thread A calls account.deposit() (a synchronized instance method) while thread B calls Account.audit() (a static synchronized method). Do they exclude each other?

    An instance synchronized method uses this, a static one uses the Class object. Data shared by both kinds of methods must be guarded by one common lock.
  3. 3. A field volatile int hits is incremented with hits++ by 4 threads, 1000 times each. What is the final value?

    volatile makes each read and write visible, but ++ is still a separate read and write, so updates can be lost. Use AtomicInteger or a lock.
  4. 4. A synchronized method calls another synchronized method on the same object. What happens?

    A thread that holds a monitor can enter it again; the JVM counts the holds and releases the lock when the outermost block exits.
  5. 5. Which statement about happens-before is true?

    Thread termination happens-before a successful join. Plain writes have no visibility guarantee, lock guarantees only apply to the same monitor, and sleep has no memory effects.

Summary

  • A race condition happens when threads interleave read-modify-write or check-then-act steps on shared data; results vary from run to run.
  • synchronized methods and blocks use an object's intrinsic lock so only one thread at a time runs the critical section; locks are released even on exceptions.
  • Instance methods lock this, static methods lock the Class, blocks lock the object you name. Every access to shared state must use the same lock; prefer a private final lock object.
  • Intrinsic locks are reentrant. Keep critical sections short and never block or do I/O inside them.
  • Visibility is a separate problem: without synchronization, a thread may never see another's writes. volatile guarantees visibility but not atomicity.
  • Happens-before rules (locks, volatile, start, join) define when writes are visible. Prefer not sharing, immutable objects and java.util.concurrent classes.

Next: Inter-Thread Communication: wait and notify, where threads stop competing and start cooperating.