Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

What outcomes are possible here and how do you fix it?

Java
class Task {
boolean ready;
int value;
void writer(){
value = 42;
ready = true;
}
void reader(){
while (!ready) {} System.out.println(value);
}
}

with writer and reader on different threads.

With no synchronization there is no happens-before between writer and reader, so this is a data race: the reader may spin forever because the JIT can hoist the read of ready out of the loop, or it may see ready as true and still print 0 because the two writes became visible out of order. Declaring ready volatile fixes both problems: value = 42 happens-before the volatile write of ready, which happens-before the read that sees true, so the reader is guaranteed to print 42.

Why this question is asked

This little class is the standard example of why concurrent Java code needs more than correct-looking logic. Read top to bottom, it is obviously right: write the value, raise the flag, wait for the flag, print the value. Yet the Java Memory Model allows it to hang or to print the wrong number, and both outcomes really happen on real JVMs. Interviewers use it to check that we can reason about visibility and reordering, and that we know the smallest correct fix. In this answer, we will list the possible outcomes, see exactly why each one can happen, apply the fix, and trace why the fix works.

1The Code and What We Expect

Here is the class laid out normally, with one thread calling writer() and another calling reader().

Java
class Task {
boolean ready;
int value;
void writer() {
value = 42;
ready = true;
}
void reader() {
while (!ready) { } // spin until the flag is set
System.out.println(value); // we expect 42
}
}

If the threads simply took turns on one shared memory, the reader would spin a little, see ready become true, and print 42. But the fields are plain fields, written and read by different threads with no synchronization at all. In the language of the memory model, there is no happens-before edge between the writer's actions and the reader's actions, and a pair of accesses like that, where one is a write, is a data race. For a racy program, the JMM allows reads to return values that look impossible from the source code.

2Outcome 1: The Reader Loops Forever

The first surprise comes from the JIT compiler, the part of the JVM that turns hot bytecode into machine code. Looking only at the reader thread, nothing inside the loop writes ready, and there is no synchronization that could make another thread's write visible. So the compiler is allowed to read ready once and reuse that value, a transformation called hoisting the read out of the loop.

Java
// What the JIT is allowed to turn reader() into
void reader() {
boolean r = ready; // read once: false
while (!r) { } // never reads the field again: infinite loop
System.out.println(value);
}

This is not a theoretical concern. With HotSpot, a loop like this, once compiled, commonly spins forever even though the writer finished long ago. It often works in a quick test because the loop is still running in the interpreter, which reads the field every time, and then fails in production once the code is hot. That difference between a test run and a long-running service is what makes such bugs hard to find.

3Outcome 2: The Reader Prints 0

The second surprise is reordering. Inside writer(), the two writes are to different fields and do not depend on each other. Neither the compiler nor the CPU has to keep them in order, because a single thread cannot tell the difference. The compiler may swap them, or the CPU may make the write of ready visible to other cores before the write of value, for example through its store buffer on a weakly ordered processor such as ARM.

So the reader can see ready as true while value is still the default 0 from its point of view. The reader's own reads may also be reordered: it could effectively read value before it read ready. Either way, the program prints 0. The third possible outcome is the one we wanted, printing 42, and without synchronization we cannot predict which of the three we get.

Possible outcomes without volatile
OutcomeCauseAllowed by the JMM?
Prints 42Writes seen in order, read not hoistedYes
Prints 0ready seen before value, writes reorderedYes
Never prints, spins foreverJIT hoisted the read of readyYes

4The Fix: Make ready volatile

The smallest correct fix is one keyword. volatile tells the JVM that this field is used for communication between threads.

Java
class Task {
volatile boolean ready;
int value; // can stay a plain field
void writer() {
value = 42; // (1)
ready = true; // (2) volatile write
}
void reader() {
while (!ready) { } // (3) volatile read, re-read on every iteration
System.out.println(value); // (4) prints 42, guaranteed
}
}

volatile fixes the infinite loop because every volatile read must actually read the variable, so the JIT can no longer hoist it out of the loop, and a volatile write must become visible to other threads. It fixes the 0 because of how it orders surrounding writes, which we trace next.

Notice that value does not need to be volatile. One volatile field, used correctly, is enough to publish any number of plain writes made before it.

5Why the Fix Works: Tracing the Happens-Before Chain

The memory model gives us three edges. Write (1) happens-before write (2) by program order, because they are in the same thread. Write (2) happens-before the read (3) that sees true, by the volatile rule: a volatile write happens-before every later read of that variable. Read (3) happens-before read (4) by program order in the reader thread. Happens-before is transitive, so (1) happens-before (4), and the reader must see 42.

In implementation terms, the JVM forbids moving the write of value after the volatile write, and forbids moving the read of value before the volatile read, and it emits whatever CPU barriers the platform needs to make that true.

Step throughWriter and reader with volatile ready
WriterMemoryReader
value = 42 (plain)
ready = true (volatile, release)
read ready: false, spin
read ready: true (acquire)
value seen as 42

5 messages in order. Play them, or step through them one at a time.

The volatile write and the read that sees it form the edge that carries value along.

6Other Correct Fixes

volatile is the lightest fix, but not the only one. We could make both methods synchronized on the same object, but then the reader must release the lock inside its loop, or the writer can never enter; a spinning loop under a lock is a deadlock waiting to happen. Better alternatives exist when we need to wait rather than spin. An AtomicBoolean works like a volatile flag. A CountDownLatch lets the reader block without burning CPU, and a CompletableFuture<Integer> carries the value itself, so the flag disappears altogether: the writer calls complete(42) and the reader calls join(). For a busy-wait loop that must stay, adding Thread.onSpinWait() inside it hints to the CPU that we are spinning, which saves power and helps the other hardware thread on the core.

7Follow-up questions

Would making value volatile instead of ready also work?

No. The edge must be created by the variable the reader actually waits on. If only value is volatile, the reader's read of ready is still a plain racy read that can be hoisted, so it can still spin forever. And seeing ready as true would not imply anything about value, because the write of ready comes after the volatile write and is not ordered by it for the reader.

Why does the code often work on x86 even without volatile?

x86 keeps stores in order and loads in order, so the 0 outcome from hardware reordering is rare there, although the JIT can still reorder the writes. The infinite loop from hoisting happens on x86 too, because it is a compiler transformation. The race is a bug on every platform; x86 only hides part of it.

Is a busy-wait loop on a volatile flag good practice?

Only in narrow cases, such as very short waits in low-latency code where blocking would cost more. In normal application code it wastes a core. Blocking tools such as CountDownLatch or a CompletableFuture are better, and they give the same visibility guarantee as volatile.

8Conclusion

In this answer, we saw that without synchronization the reader may spin forever because the JIT hoists the read of ready, or print 0 because the writes become visible out of order, and that the JMM allows both because the program has a data race. Declaring ready volatile fixes both: the read can no longer be hoisted, and the chain from value = 42 through the volatile write and the read that sees true guarantees that the reader prints 42.

What to say in the interviewAbout 80 seconds aloud

Open with

There is no synchronization between the two threads, so there is no happens-before edge between the writer and the reader, and that makes this a data race. Three outcomes are possible.

Then, if they want more

It may print 42, as intended. It may loop forever, because nothing in the loop changes ready, so the JIT is allowed to read the field once and keep using the cached false; this happens in practice once the method is compiled.

And it may print 0, because the writes to value and ready are independent, so the compiler or the CPU can make ready visible before value, and the reader sees the flag but not the data. The fix is to declare ready volatile. A volatile read must actually read the field each time, so the loop terminates.

And the volatile rule gives a chain: value = 42 happens-before the volatile write of ready by program order, that write happens-before the read that sees true, and that read happens-before printing value, so by transitivity the reader must print 42. value itself can stay a plain field.

In real code, if the reader needs to wait rather than spin, I would use a CountDownLatch or a CompletableFuture that carries the value, which gives the same visibility guarantee without burning a core.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JLS chapter 17, Threads and Locks
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What outcomes are possible here and how do you fix it?": https://scrivio-interview-library.netlify.app/java/java-memory-model/dab9c973df/