Sub topic 5
Protecting Shared State with synchronized and Atomic Variables
In the last chapter you saw two threads add to the same counter, and the final total came out wrong. That is a race condition: the result depends on the timing of the threads. This chapter shows three Java tools that fix it:
synchronized, which lets only one thread at a time run a piece of code.volatile, which makes sure every thread sees the newest value of a variable.- Atomic variables, such as
AtomicInteger, which do small updates safely in one step.
You will learn what each tool does, when to use it, and the mistakes beginners often make with it.
Why `count++` Breaks
The line count++ looks like one action. The computer actually does three:
- Read the current value of
count. - Add 1 to it.
- Write the new value back.
Two threads can both read the value 5, both add 1, and both write 6. Two increments happened, but the counter only went up by one. To fix this, the three steps must act as one step that no other thread can break into. A step like that is called atomic. Atomic means "cannot be split."
There is a second, quieter problem called visibility. A thread may keep a copy of a variable in a fast, private spot, such as a CPU cache. Another thread may then keep seeing an old value for a long time. A fix for shared data has to solve both problems: the steps must be atomic, and every thread must see the latest value.
The `synchronized` Keyword
Locks in plain words
Every Java object has a built-in lock, also called a monitor. A lock is like the key to a single-person room. A thread must hold the key to enter. If another thread already has it, the new thread waits outside until the key is returned.
When you mark a method synchronized, a thread must take the object's lock before it runs the method. It gives the lock back when the method ends, including when the method throws an exception.
Synchronized methods
Here is a counter that is safe to share:
public class SyncCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
}Both methods lock the same object, the SyncCounter instance. So while one thread is inside increment, no other thread can run increment or get on that counter. The read-add-write steps can no longer interleave. Interleave means the steps of two threads get mixed together.
Marking get as synchronized matters too. Taking and releasing a lock also solves visibility. When a thread releases a lock, its changes become visible to the next thread that takes the same lock. If get were not synchronized, a reader might see a stale (old) value.
Here is a full program you can run:
public class SyncCounterDemo {
static 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 prints count: 200000 every time.
Synchronized blocks
Sometimes only a few lines in a method touch shared data. You can lock just those lines with a synchronized block:
import java.util.ArrayList;
import java.util.List;
public class BlockDemo {
private final Object lock = new Object();
private final List<String> log = new ArrayList<>();
public void record(String message) {
String line = System.currentTimeMillis() + " " + message;
synchronized (lock) {
log.add(line);
}
}
public int size() {
synchronized (lock) {
return log.size();
}
}
public static void main(String[] args) throws InterruptedException {
BlockDemo demo = new BlockDemo();
Runnable work = () -> {
for (int i = 0; i < 1_000; i++) {
demo.record("event " + i);
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("entries: " + demo.size());
}
}Building the line string does not touch shared data, so it happens outside the lock. Only log.add is protected. Keeping the locked part small means threads spend less time waiting for each other.
The object in parentheses is the lock. Here it is a private Object named lock. A private lock is a good habit, because code outside your class cannot grab it and block you by accident.
What `synchronized` locks
| You write | The lock used |
|---|---|
| `synchronized void m()` (instance method) | The object `this` |
| `static synchronized void m()` | The class object, such as `SyncCounter.class` |
| `synchronized (obj) { ... }` | The object `obj` |
A static synchronized method and an instance synchronized method use different locks. They do not block each other.
The `volatile` Keyword
volatile is a word you put on a field. It solves visibility only. Every read of a volatile field sees the latest value written by any thread.
A common use is a stop flag:
public class VolatileFlagDemo {
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("Worker stopped after " + loops + " loops");
});
worker.start();
Thread.sleep(500);
running = false;
worker.join();
}
}Without volatile, the worker might never notice that running became false, and the program could hang forever. With volatile, the worker sees the change and stops.
Atomic Variables
The package java.util.concurrent.atomic has classes such as AtomicInteger, AtomicLong, AtomicBoolean, and AtomicReference. Each one wraps a single value and gives you methods that update it in one atomic step. They also solve visibility, just like volatile.
Most of them work without a lock. They use a special CPU instruction called compare-and-set (CAS). CAS says: "If the value is still what I expect, change it to my new value. If not, tell me I failed." When a thread fails, it simply tries again. Threads never sit blocked waiting for a key, so atomics are usually fast for simple updates.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
public static void main(String[] args) throws InterruptedException {
AtomicInteger hits = new AtomicInteger();
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
hits.incrementAndGet();
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("hits: " + hits.get());
hits.addAndGet(10);
hits.updateAndGet(n -> n * 2);
boolean changed = hits.compareAndSet(400020, 0);
System.out.println("changed: " + changed + ", now: " + hits.get());
}
}This prints hits: 200000, then changed: true, now: 0.
Useful AtomicInteger methods:
| Method | What it does |
|---|---|
| `get()` | Reads the current value |
| `set(v)` | Writes a new value |
| `incrementAndGet()` | Adds 1 and returns the new value |
| `getAndIncrement()` | Adds 1 and returns the old value |
| `addAndGet(d)` | Adds `d` and returns the new value |
| `updateAndGet(f)` | Applies the function `f` and returns the new value |
| `compareAndSet(expect, v)` | Sets to `v` only if the value equals `expect` |
Choosing the Right Tool
| Tool | Solves visibility | Makes updates atomic | Threads wait? | Best for |
|---|---|---|---|---|
| `volatile` | Yes | No | No | Stop flags, status values |
| Atomic classes | Yes | Yes, for one variable | No, they retry | Counters, single shared values |
| `synchronized` | Yes | Yes, for any block of code | Yes | Several fields that must change together |
For example, a bank transfer takes money from one account and adds it to another. Both changes must happen together, so two separate atomic variables are not enough. Here you need synchronized.
Common Mistakes
- Locking only the writes. If reads are not synchronized, readers can see old values. Protect reads with the same lock.
- Locking on a new object each time. Code like
synchronized (new Object())gives every thread its own lock, so it protects nothing. - Locking too much. Putting slow work, like file reading or
Thread.sleep, inside a lock makes the other threads wait for no reason. - Mixing locks. One piece of data needs one lock. Write down which lock guards which field.
- Taking two locks in different orders. If Thread A holds lock X and waits for Y, while Thread B holds Y and waits for X, both wait forever. This is called a deadlock. Always take multiple locks in the same order.
Exercise
A class has a field private volatile int visitors = 0; and a method void arrive() { visitors++; }. Many threads call arrive(). Is the count always correct? If not, give two ways to fix it.
Show answer
No. volatile makes each read and write visible, but visitors++ is still three steps (read, add, write), so two threads can lose an update. Fix 1: change the field to private final AtomicInteger visitors = new AtomicInteger(); and call visitors.incrementAndGet(). Fix 2: make arrive() (and any method that reads visitors) synchronized.
Exercise
A class has public synchronized void deposit(int x) and public static synchronized void reset(), and both change the same static field. Can they run at the same time on two threads?
Show answer
Yes. The instance method locks this, while the static method locks the class object. They use different locks, so they do not block each other and the static field can be corrupted. Both methods should use one shared lock, for example by making both static synchronized or by using a single private static lock object in synchronized blocks.
Exercise
Why is synchronized (new Object()) { count++; } useless for protecting count?
Show answer
Each call creates a brand-new object, so each thread locks a different object. No thread ever has to wait for another, and the increments can still interleave. The lock object must be shared, such as a private final Object lock field.