Ch. 7 · Java

Java Thread Visibility and Happens-Before

Java Thread Visibility and Happens-Before. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Cross-thread reads require appropriate synchronization to make updates reliably visible. Atomicity and visibility are related but different guarantees.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: Volatile publishes a flag’s updates but does not make a compound increment atomic. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Identify shared access

A writer and reader need a defined happens-before relationship.

Step 2: Separate guarantees

Volatile visibility does not make read-modify-write increments atomic.

Step 3: Protect the full operation

Use AtomicInteger or a shared lock according to the larger invariant.

Worked scenario

Volatile publishes a flag’s updates but does not make a compound increment atomic.

Two threads can both read counter value four and each write five with an ordinary compound increment, losing one update. Making the field volatile does not combine those steps. AtomicInteger.incrementAndGet provides the atomic counter operation, but cannot alone protect additional related fields.

Common mistake

A loop reading an unsynchronized flag can fail to observe a writer’s update.

Verify the behavior

Run concurrent increments and verify the final total; use code reasoning alongside repeated stress tests.

Interview exercise

Implement a shared counter.

Answer and reasoning

Use AtomicInteger or protect the compound operation with a lock, depending on the broader invariant.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc