Chapter 75 of 77

Thread Synchronization in Java

In the previous chapter, we created multiple threads and watched them run concurrently. As long as each thread works on its own data, everything is fine. But real programs often have threads that share data: two users booking the last seat on a train, two ATMs withdrawing from the same bank account, or many requests updating the same visitor counter.

When several threads read and modify the same data at the same time, results can become wrong in ways that are hard to reproduce. Thread synchronization is how we prevent this.

Synchronization controls how multiple threads access shared data, so that only one thread at a time can run a critical piece of code, and changes made by one thread are visible to the others.

Quick Recap: join()

We will use join() from the previous chapter a lot. t.join() makes the current thread wait until thread t finishes. We will use it so that main() prints the final result only after the worker threads are done.

t1.start();
t1.join();   // main waits here until t1 has finished
System.out.println("t1 is done");

Like Thread.sleep(), join() can throw InterruptedException, so we either catch it or declare it with throws.

The Problem: A Race Condition

Let's have two threads each increment a shared counter 100,000 times. We expect the final count to be 200,000:

class Counter {
    private int count = 0;

    void increment() {
        count++;
    }

    int getCount() {
        return count;
    }
}

class Main {
    public static void main(String[] args) throws InterruptedException {

        Counter counter = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();

        t1.join();   // wait for t1 to finish
        t2.join();   // wait for t2 to finish

        System.out.println("Count = " + counter.getCount());
    }
}

Running it three times gave:

Count = 144413
Count = 119064
Count = 152722

Your numbers will be different, and they change on every run, but they are almost never 200,000. Some increments were lost.

Why Does count++ Go Wrong?

count++ looks like one step, but the computer actually does three separate steps:

1. READ   the current value of count
2. ADD    1 to it
3. WRITE  the new value back

If two threads interleave these steps, one update can overwrite the other:

count = 5

Thread 1: READ  count   → 5
Thread 2: READ  count   → 5
Thread 1: ADD 1         → 6
Thread 2: ADD 1         → 6
Thread 1: WRITE count   → 6
Thread 2: WRITE count   → 6     ← should be 7, one increment is lost!

This is called a race condition: the result depends on the unpredictable timing of threads. The section of code that touches shared data (here, count++) is called a critical section. We need to make sure only one thread is inside it at a time.

The synchronized Keyword

Every Java object has a built-in lock, also called a monitor or intrinsic lock. When a thread enters a synchronized method, it must first acquire that object's lock. If another thread already holds it, the new thread waits until the lock is released.

The fix is just one keyword:

class Counter {
    private int count = 0;

    synchronized void increment() {
        count++;
    }

    synchronized int getCount() {
        return count;
    }
}

Now the same program prints:

Count = 200000

every single time. Think of the lock like the key to a single bathroom: whoever holds the key goes in, and everyone else waits outside until the key is returned.

Thread 1: acquire lock → READ, ADD, WRITE → release lock
Thread 2:   (waiting...)                        acquire lock → READ, ADD, WRITE → release lock

Some important details:

  • A synchronized instance method locks on this (the current object). Two threads using two different Counter objects do not block each other.

  • A synchronized static method locks on the class itself (Counter.class), shared by all objects.

  • The lock is released automatically when the method returns, even if it throws an exception.

  • Java locks are reentrant: a thread that already holds a lock can enter other synchronized methods on the same object without blocking itself.

Synchronized Blocks

Synchronizing a whole method can be wasteful if only a few lines touch shared data. A synchronized block locks only the critical section, using any object as the lock:

class BankAccount {
    private int balance = 1000;
    private final Object lock = new Object();

    void withdraw(String who, int amount) {
        System.out.println(who + " is checking the balance");   // no lock needed

        synchronized (lock) {
            if (balance >= amount) {
                balance -= amount;
                System.out.println(who + " withdrew " + amount + ", balance = " + balance);
            } else {
                System.out.println(who + " failed: insufficient balance");
            }
        }
    }
}

class Main {
    public static void main(String[] args) throws InterruptedException {

        BankAccount account = new BankAccount();

        Thread john = new Thread(() -> account.withdraw("John", 800));
        Thread priya = new Thread(() -> account.withdraw("Priya", 800));

        john.start();
        priya.start();
        john.join();
        priya.join();
    }
}

One possible output:

John is checking the balance
Priya is checking the balance
John withdrew 800, balance = 200
Priya failed: insufficient balance

The order of names can change between runs, but only one withdrawal ever succeeds. Without the lock, both threads could pass the balance >= amount check before either one subtracts, and the account would go to -600. This "check-then-act" pattern is one of the most common sources of race conditions.

Using a private final lock object is a good habit: outside code cannot accidentally lock on it and interfere with your class.

Visibility and the volatile Keyword

Race conditions are not the only problem. For speed, each thread may keep a cached copy of a variable, and the JIT compiler may optimise loops based on that. So a change made by one thread might never be seen by another thread.

class Worker extends Thread {
    private volatile boolean running = true;

    @Override
    public void run() {
        long loops = 0;
        while (running) {
            loops++;
        }
        System.out.println("Worker stopped");
    }

    void stopWorking() {
        running = false;
    }
}

class Main {
    public static void main(String[] args) throws InterruptedException {

        Worker worker = new Worker();
        worker.start();

        Thread.sleep(500);
        worker.stopWorking();
        worker.join();

        System.out.println("Main finished");
    }
}

Output:

Worker stopped
Main finished

Without volatile, this program may never finish. When we tested it without volatile, it hung: the worker kept looping forever because it never saw running become false. (This behaviour depends on the JVM and the machine, which is exactly what makes visibility bugs so dangerous.) Declaring the field volatile guarantees that every read sees the most recent write from any thread.

But be careful: volatile only fixes visibility. It does not make count++ safe, because read-add-write is still three steps. Use volatile for simple flags that one thread writes and others read. (synchronized gives you both mutual exclusion and visibility.)

Atomic Variables

For simple counters, the java.util.concurrent.atomic package offers classes like AtomicInteger and AtomicLong. Their operations are performed as one indivisible (atomic) step, without locking:

import java.util.concurrent.atomic.AtomicInteger;

class Main {
    public static void main(String[] args) throws InterruptedException {

        AtomicInteger count = new AtomicInteger(0);

        Runnable task = () -> {
            for (int i = 0; i < 100_000; i++) {
                count.incrementAndGet();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Count = " + count.get());
    }
}

Output:

Count = 200000

Useful methods include get(), set(), incrementAndGet(), getAndIncrement(), addAndGet(n), and compareAndSet(expected, newValue).

ReentrantLock: A More Flexible Lock

The java.util.concurrent.locks.ReentrantLock class does the same job as synchronized, but with extra features such as tryLock() (try to get the lock without waiting forever) and fairness options. The catch is that you must release it yourself, always in a finally block:

import java.util.concurrent.locks.ReentrantLock;

class TicketCounter {
    private int tickets = 3;
    private final ReentrantLock lock = new ReentrantLock();

    void book(String name) {
        lock.lock();
        try {
            if (tickets > 0) {
                tickets--;
                System.out.println(name + " booked a ticket. Left: " + tickets);
            } else {
                System.out.println(name + ": sold out");
            }
        } finally {
            lock.unlock();   // always release, even if an exception occurs
        }
    }
}

If five users try to book at once, exactly three succeed and two see "sold out". Which users win changes from run to run, for example:

John booked a ticket. Left: 2
Priya booked a ticket. Left: 1
Neha booked a ticket. Left: 0
Jason: sold out
Alex: sold out

Forgetting unlock() (or not putting it in finally) leaves the lock held forever, and every other thread waits endlessly. For most everyday code, synchronized is simpler and perfectly fine.

Deadlock

Locks solve race conditions but introduce a new danger. A deadlock happens when two threads each hold a lock and wait forever for the lock held by the other:

Thread t1 = new Thread(() -> {
    synchronized (lockA) {
        System.out.println("T1 holds A, waiting for B");
        sleep(100);
        synchronized (lockB) {
            System.out.println("T1 got B");
        }
    }
});

Thread t2 = new Thread(() -> {
    synchronized (lockB) {
        System.out.println("T2 holds B, waiting for A");
        sleep(100);
        synchronized (lockA) {
            System.out.println("T2 got A");
        }
    }
});

Output (and then the program hangs forever):

T1 holds A, waiting for B
T2 holds B, waiting for A

(Here sleep() is a small helper method that calls Thread.sleep() and catches the exception.)

T1 ──holds──▶ lockA        T1 ──waits for──▶ lockB
T2 ──holds──▶ lockB        T2 ──waits for──▶ lockA
              Nobody can continue: deadlock!

How to avoid deadlocks:

  • Lock ordering: always acquire multiple locks in the same order (for example, always A then B). This single rule prevents the deadlock above.

  • Hold locks for as short a time as possible, and avoid calling unknown code while holding a lock.

  • Use tryLock() with a timeout so a thread can give up instead of waiting forever.

Thread Communication: wait() and notifyAll()

Sometimes a thread must wait for a condition, not just a lock. For example, a consumer should wait until a producer has put something in a box. Every object has wait(), notify(), and notifyAll() methods for this. They can only be called while holding that object's lock (inside synchronized).

class Mailbox {
    private String message;          // null means empty

    synchronized void put(String msg) throws InterruptedException {
        while (message != null) {    // box is full → wait
            wait();
        }
        message = msg;
        notifyAll();                 // wake up a waiting reader
    }

    synchronized String take() throws InterruptedException {
        while (message == null) {    // box is empty → wait
            wait();
        }
        String msg = message;
        message = null;
        notifyAll();                 // wake up a waiting writer
        return msg;
    }
}

If a producer thread puts "Order #1", "Order #2", "Order #3", and then "DONE", and a consumer thread takes messages until it sees "DONE", the output is:

Processing Order #1
Processing Order #2
Processing Order #3
All orders processed

wait() releases the lock and sleeps until another thread calls notifyAll() on the same object. Always call wait() inside a while loop that re-checks the condition, never an if, because a thread can wake up when the condition is still not true. In real projects, ready-made classes like BlockingQueue (from java.util.concurrent) handle this for you.

Thread-Safe Collections

Classes like ArrayList and HashMap are not thread-safe. If several threads modify them at once, data can be lost or the collection can become corrupted. Safer alternatives:

Instead of

Use

HashMap

ConcurrentHashMap

ArrayList (mostly read)

CopyOnWriteArrayList

ArrayList (general)

Collections.synchronizedList(new ArrayList<>())

Queue between producer and consumer

ArrayBlockingQueue, LinkedBlockingQueue

Choosing the Right Tool

Tool

Mutual exclusion

Visibility

Best for

synchronized

Yes

Yes

General critical sections

volatile

No

Yes

Simple flags (stop, ready)

AtomicInteger etc.

Yes, for single operations

Yes

Counters and single values

ReentrantLock

Yes

Yes

When you need tryLock(), timeouts, or fairness

Common Mistakes

1. Synchronizing on different objects
   → two threads using different locks do not block each other at all

2. Using volatile for count++
   → visibility is fixed, but increments are still lost

3. Synchronizing only the write, not the read
   → readers may see stale values

4. Calling wait() with "if" instead of "while"
   → the thread may continue when the condition is false

5. Forgetting lock.unlock() in a finally block
   → the lock is never released

6. Acquiring locks in different orders
   → deadlock

The Main Idea

When threads share mutable data, unsynchronized access causes race conditions and visibility problems. Use synchronized, locks, atomic variables, or thread-safe collections so that only one thread modifies the data at a time and all threads see the latest values.

Interview favourites from this chapter: What is a race condition? Why is count++ not thread-safe? What is the difference between synchronized and volatile? What is a deadlock and how do you prevent it? Why must wait() be called in a loop? In the next chapter, you will learn how to manage many threads easily using the Executor framework and Java's modern virtual threads.