Thread Synchronization
Site Admin
· 11 Sep 2026
· 11 views
The Shared Data Problem
When two threads read and write the same variable at the same time, the value can become corrupted. Run this long enough and the total goes wrong.
class Counter {
int count = 0;
void increment() { count++; } // not atomic!
}The expression count++ is really three steps: read, add, write back. Between two threads these steps can interleave, losing an update.
Fix with synchronized
class Counter {
int count = 0;
synchronized void increment() { count++; }
}Anything inside a synchronized method holds a lock, so only one thread can be inside it at a time. The read-add-write sequence becomes effectively one unit.
Atomic Classes
For simple counters, java.util.concurrent.atomic is faster and simpler:
import java.util.concurrent.atomic.AtomicInteger;
class Counter {
AtomicInteger count = new AtomicInteger();
void increment() { count.incrementAndGet(); }
}The volatile Keyword
volatile tells the JVM: always read this variable from main memory, never a cached copy. It guarantees visibility but not atomicity.
class RunningFlag {
volatile boolean running = true;
}A Practical Pattern
Counter shared = new Counter();
Thread a = new Thread(() -> { for (int i = 0; i < 1000; i++) shared.increment(); });
Thread b = new Thread(() -> { for (int i = 0; i < 1000; i++) shared.increment(); });
a.start(); b.start();
a.join(); b.join();
System.out.println(shared.count); // reliably 2000Key Points
- Shared mutable state needs protection from concurrent updates.
synchronizedprovides mutual exclusion with a lock.- Prefer atomic classes for counters; use
volatilefor simple flags.