Sub topic 5
Protecting Shared State with synchronized and Atomic Variables
In the last chapter, two threads added to the same counter, and the final total came out wrong. That bug is called a race condition. This chapter shows three tools that fix it: synchronized, volatile, and atomic variables.
Why the Counter Broke
count++ looks like one step, but the computer does three:
- Read the value of
count. - Add 1.
- Write the new value back.
If two threads both read 5 before either one writes, both write 6. One update is lost. To prevent this, only one thread at a time should be allowed to run those three steps.
The synchronized Keyword
A lock is a marker that only one thread can hold at a time. Every Java object has one built in. The synchronized keyword makes a thread take an object's lock before it runs some code. It releases the lock when it is done.
If another thread already holds the lock, the new thread waits. The waiting thread is blocked: it is paused until the lock is free.
public class SyncCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
public static void main(String[] args) throws InterruptedException {
SyncCounter counter = new SyncCounter();
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
counter.increment();
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("count: " + counter.get());
}
}This program always prints count: 200000. Both methods lock the same object (this), so increments cannot overlap. Because get is also synchronized, it always sees the latest value.
Synchronized Blocks
You can lock only part of a method with a synchronized block. This keeps the locked section small, so other threads wait less.
public class BlockCounter {
private final Object lock = new Object();
private int count = 0;
public void increment() {
// work that does not touch count could go here, unlocked
synchronized (lock) {
count++;
}
}
}The volatile Keyword
Threads can keep their own cached copy of a variable. A cached copy is a saved copy that may be out of date. So one thread may never see another thread's change. Marking a field volatile tells Java that every read must see the most recent write.
public class StopFlagDemo {
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long loops = 0;
while (running) {
loops++;
}
System.out.println("Stopped after " + loops + " loops");
});
worker.start();
Thread.sleep(500);
running = false;
worker.join();
}
}Without volatile, the worker might loop forever. However, volatile does not make count++ safe. It fixes visibility, meaning whether a thread can see a change. It does not fix the read-add-write problem.
Atomic Variables
An atomic operation happens all at once. No other thread can see it half done. The java.util.concurrent.atomic package has classes like AtomicInteger and AtomicLong. They do safe updates without you writing any lock.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
public static void main(String[] args) throws InterruptedException {
AtomicInteger count = new AtomicInteger();
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
count.incrementAndGet();
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("count: " + count.get());
}
}Choosing a Tool
| Tool | Fixes visibility | Fixes read-add-write | Best for |
|---|---|---|---|
| `volatile` | Yes | No | A simple flag one thread sets and others read |
| Atomic classes | Yes | Yes | A single counter or value |
| `synchronized` | Yes | Yes | Several variables that must change together |
Exercise
A field is declared private volatile int hits = 0; and many threads run hits++. Is the final total always correct? What would you change?
Show answer
No. volatile makes changes visible, but hits++ is still three separate steps, so updates can be lost. Use an AtomicInteger with incrementAndGet(), or do the increment inside a synchronized method or block that every thread locks on the same object.
Exercise
One method uses synchronized (this) and another uses synchronized (lock). Both change the same field. Is the field protected?
Show answer
No. The methods hold different locks, so they can run at the same time. Both must synchronize on the same object.