Quiz: volatile in Java: Java Memory Model and happens-before

Total: 8 questions

1. 

What does the volatile keyword guarantee in Java, and what doesn't it guarantee?

volatile is a field modifier that gives two guarantees:

  • Visibility: a write to the field becomes visible to every thread that reads it afterwards.
  • Ordering: the compiler, the JIT and the CPU don't move ordinary reads and writes across a volatile access, so along with the new value the reader sees everything the writer did before the write.

What volatile doesn't give you is mutual exclusion or atomicity of compound operations. Single reads and writes of a volatile field are atomic (including long and double), but count++, count += 5 or flag = !flag are still three read-modify-write steps, and another thread can slip in between them. Those need synchronized or atomic classes such as AtomicInteger.

2. 

Why can a thread fail to see a value written by another thread without volatile?

There are three reasons, and all of them are legal optimizations that are invisible within a single thread:

  • The JIT compiler sees that nobody writes the field inside the loop and reads it once, keeping the value in a register. The loop while (running) n++; effectively becomes if (running) { while (true) n++; }.
  • The CPU: a write first lands in the core's store buffer and cache, and without memory barriers it isn't defined when, or in what order, other cores will see it.
  • Reordering: the compiler, the JIT and the CPU change the order of independent operations for speed.

That's why a stop flag without volatile may not work: on HotSpot the program often never finishes, though that isn't the only possible outcome - the JMM simply promises nothing here. The "working memory" and "main memory" of older textbooks are an abstraction from the first edition of the specification, not a description of real hardware.

3. 

What are the Java Memory Model and the happens-before relation?

The Java Memory Model (JMM) is the part of the language specification (JLS, chapter 17) that defines which values a read of a shared variable may return in a multithreaded program. The current model arrived in Java 5 with JSR-133.

Its central concept is happens-before: if action A happens-before action B, then B is guaranteed to see the results of A. It doesn't mean "happened earlier in time"; it's a guarantee of visibility and ordering. Two actions may run one after the other by the clock, but without happens-before the second is allowed not to see the first.

Two accesses to the same variable from different threads, at least one of them a write, that aren't ordered by happens-before form a data race. A program without data races behaves as if it were sequentially consistent.

Don't confuse the JMM with the JVM's memory structure: the memory model is a set of visibility rules between threads, while the stack, the heap and Metaspace are areas where data lives.

4. 

What happens-before rules does the Java Memory Model define?

  • Program order: each action of a thread happens-before every action that follows it in the same thread.
  • Monitor: unlocking a monitor happens-before every subsequent lock of the same monitor.
  • volatile: a write to a volatile field happens-before every subsequent read of that same field.
  • Thread.start(): a call to t.start() happens-before any action in thread t.
  • Thread termination: any action of thread t happens-before a successful return from t.join() or seeing t.isAlive() == false.
  • interrupt(): a call to t.interrupt() happens-before t detects the interrupt.
  • Transitivity: if A hb B and B hb C, then A hb C.

A separate guarantee from JLS 17.5 covers final fields: their values set in the constructor are visible to any thread that obtains a reference, as long as the constructor didn't leak this.

The key word in every rule is "same": a write to volatile field a guarantees nothing to a thread reading volatile field b.

5. 

How do you safely hand data to another thread with a volatile flag?

The thread first fills in the ordinary fields and then writes the volatile flag. A thread that reads the new flag value is guaranteed to see the ordinary fields too:

data = 42;      // (1) plain write
ready = true;   // (2) volatile write

The chain: (1) happens-before (2) by program order, (2) happens-before the read that sees ready == true by the volatile rule, and that read happens-before the read of data by program order in the reader thread. By transitivity the reader sees data = 42. The technique is called piggybacking: riding on someone else's synchronization.

The order of the lines matters: swap them, and the reader may see ready == true and data == 0. The guarantee is one-directional - it covers writes before the volatile write and reads after the volatile read; changes to data after ready = true may stay invisible to the reader.

6. 

Can you replace synchronized with volatile, and when is volatile enough?

Only if the block's sole job is to make a write visible and the operation itself is already atomic: a single assignment that doesn't read the old value. volatile gives visibility and ordering for one field without locking; synchronized gives visibility plus mutual exclusion for a whole block.

volatile is enough for a stop flag, a reference to a ready immutable object that is replaced as a whole, and the "one thread writes, many read" pattern.

volatile is not enough for a counter shared by several threads (count++), "check, then act" (if not initialized, initialize), or an invariant spanning several fields such as lower <= upper. These need synchronized, atomic classes, or one immutable object behind a volatile reference.

7. 

Why does double-checked locking need volatile, and what can replace the idiom?

Double-checked locking creates a singleton lazily and acquires the monitor only on the first call. The first check instance == null runs outside synchronized, so without volatile that read has no happens-before relation with the constructor's writes: a thread can see a non-null reference to an object whose fields aren't filled in yet.

With private static volatile Config instance the reference write becomes a volatile write, and everything the constructor did is visible to any thread that sees the reference. This is correct since Java 5.

It's simpler to skip the double check altogether and use the holder idiom:

private static class Holder {
    static final Settings INSTANCE = new Settings();
}

The Holder class is initialized on first access exactly once under a JVM lock (JLS §12.4.2), with no volatile or synchronized in the code. If you don't need laziness, a single-element enum works too.

8. 

Does volatile make array elements volatile?

No. private volatile int[] data makes only the array reference volatile: assigning a new array is visible to every thread, but data[0] = 5 is a plain write with no visibility guarantee.

For per-element volatile semantics use AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray or MethodHandles.arrayElementVarHandle(...). The safe publication trick also works: fill a new array, write its reference into a volatile field, and never modify it again.

Page 1 of 1