What one thread sees of another
Two problems hide in shared data:
- Lost updates.
count++looks like one step but is three: readcount, add one, write it back. If two threads read 41 at the same moment, both write 42, and one view is lost. - Invisible writes. For speed, each CPU core keeps copies of memory in its caches, and the JIT compiler may keep a variable in a register or reorder instructions. Without a rule that forces it, a thread may never see another thread’s write.
Java gives you three tools, from lightest to heaviest:
| Tool | Fixes | Use for |
|---|---|---|
volatile | visibility | a flag or a reference that one thread writes and others read |
AtomicInteger, AtomicLong, LongAdder | visibility and atomic updates of one value | counters, sequence numbers |
synchronized or a Lock | visibility and atomicity of a whole block | several values that must change together |
The Java Memory Model (JLS chapter 17) defines which writes a read may see. Without synchronization, the compiler, JIT and CPU may reorder and cache freely, so the only guarantees come from happens-before edges: program order within a thread, unlocking a monitor before every later lock of it, a write to a volatile field before every later read of it, Thread.start() before the started thread’s actions, a thread’s actions before another thread’s successful join(), and the java.util.concurrent hand-offs (putting into a BlockingQueue before taking out, completing a Future before get() returns). Happens-before is transitive, which is what makes “write data, then write a volatile flag; read the flag, then read data” safe. volatile gives visibility and ordering but not atomicity of compound actions; atomics add CAS-based read-modify-write; locks give mutual exclusion plus visibility for everything inside. final fields are guaranteed visible after construction if this doesn’t escape the constructor. Interviewers probe exactly these: the stop-flag bug, count++, double-checked locking, and when LongAdder beats AtomicLong.
Predict the output
Two threads each run count++ 100,000 times on a shared int field, and the main thread joins both. What does it print?
var count = 0
fun main() {
val work = Runnable { repeat(100_000) { count++ } }
val a = Thread(work)
val b = Thread(work)
a.start(); b.start()
a.join(); b.join()
println(count)
}public class Counter {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> { for (int i = 0; i < 100_000; i++) count++; };
Thread a = new Thread(work), b = new Thread(work);
a.start(); b.start();
a.join(); b.join();
System.out.println(count);
}
}Each count++ is a read, an add and a write. When both threads read the same value, one increment is lost, so the result is usually below 200,000 and changes from run to run. volatile doesn't fix it (the three steps are still separate); an AtomicInteger (incrementAndGet), a LongAdder or a synchronized block does.
private val hits = AtomicInteger()
fun hit() { hits.incrementAndGet() } // atomic, lock-free
private val views = LongAdder()
fun view() { views.increment() } // best under heavy contention; read with sum()
private var likes = 0
private val lock = Any()
fun like() = synchronized(lock) { likes++ } // one critical section
fun likes() = synchronized(lock) { likes } // reads must synchronize too, for visibilityprivate final AtomicInteger hits = new AtomicInteger();
void hit() { hits.incrementAndGet(); } // atomic, lock-free
private final LongAdder views = new LongAdder();
void view() { views.increment(); } // best under heavy contention; read with sum()
private int likes;
synchronized void like() { likes++; } // the whole method is one critical section
synchronized int likes() { return likes; } // reads must synchronize too, for visibilityThe flag nobody sees
Tap the line with the bug.
class Exporter : Runnable {
private var running = true
fun stop() { running = false }
override fun run() {
while (running) {
exportNextBatch()
}
}
}public class Exporter implements Runnable {
private boolean running = true;
public void stop() { running = false; }
@Override
public void run() {
while (running) {
exportNextBatch();
}
}
}Hint: stop() is called from a request thread; run() loops on a worker thread. What forces the worker to read the new value?
Nothing. Without volatile (or a lock), the JIT may read running once, keep it in a register and turn the loop into while (true). Whether it does depends on the JVM, the CPU and how hot the loop is, so it works in tests and fails in production: the “Stop export” button does nothing and the thread runs until the next deploy.
Declare the flag volatile, which guarantees every read sees the latest write:
@Volatile private var running = trueprivate volatile boolean running = true;Better still, use the thread’s own interrupt flag (while (!Thread.currentThread().isInterrupted()) and future.cancel(true) from the caller), which also wakes the thread from sleep and blocking queues.
Safe publication
An object is safely published when another thread can’t see it half-constructed. Unsafe: assigning a new object to a plain field that another thread reads, because the reference may become visible before the constructor’s writes. Safe: storing it in a volatile or final field, an AtomicReference, a concurrent collection, or handing it over through a BlockingQueue or Future, or initializing it in a static initializer (class initialization is synchronized). Immutable objects with all-final fields are safe even when published through a data race, which is one more reason to prefer records and immutable value objects.
Deep diveWhy double-checked locking needs volatileInterview favorite
Lazy singletons were often written like this: check instance == null, lock, check again, then instance = new Helper(). Without volatile, the assignment of the reference can become visible to another thread before the writes inside Helper’s constructor. A second thread passes the first check (not null) without locking and uses a Helper whose fields are still zero.
Since Java 5, declaring the field volatile fixes it: the volatile write happens-after the constructor, and the reader’s volatile read happens-after that write. Simpler alternatives need no reasoning at all: the holder-class idiom (static class Holder { static final Helper INSTANCE = new Helper(); }, initialized lazily and thread-safely by the class loader), an enum singleton, or, in Spring, a singleton bean.
- Only happens-before edges guarantee visibility: monitor unlock → lock, volatile write → read,
start(),join(), andjava.util.concurrenthand-offs. It’s transitive. volatile= visibility and ordering, not atomicx++. Atomics = CAS read-modify-write;LongAdderunder contention. Locks = atomicity of blocks, reads must lock too.- Safe publication:
finalfields, volatile, concurrent collections, queues; immutable objects are safe. Double-checked locking needsvolatile(or use the holder idiom).
Check this part
Why can count++ on a shared field lose updates?
A boolean stop flag is written by one thread and read in a loop by another. What does it need?
Does making the counter field volatile fix count++?
Why does double-checked locking need the instance field to be volatile?