Quick revision
The short answer
The worker never stops because running is a plain field, so the JIT may read it once and keep using the cached true. Declaring it volatile fixes that: the write in stop() becomes visible to the loop. volatile is enough when the flag is a single independent value, but not always enough to stop the worker: if doWork() blocks, the loop never gets back to the check, so we also interrupt the thread or use timeouts, and if stopping must publish other state, that state is written before the volatile write.
What to remember
In this answer, we saw that a plain stop flag can be read once and cached by the JIT, so the worker never stops, and that declaring it volatile makes stop()'s write visible to the loop. volatile is enough for a single independent flag, but not when doWork() blocks, so we also interrupt the thread or use timed calls, and when stopping must publish more state, we write that state before the volatile write so the flag carries it along.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The worker never stops because running is a plain field, so the JIT may read it once and keep using the cached true. Declaring it volatile fixes that: the write in stop() becomes visible to the loop. volatile is enough when the flag is a single independent value, but not always enough to stop the worker: if doWork() blocks, the loop never gets back to the check, so we also interrupt the thread or use timeouts, and if stopping must publish other state, that state is written before the volatile write.
Why this question is asked
Stop flags are everywhere: background pollers, consumers that read from a queue, batch workers, scheduled jobs. When one fails to stop, a deployment hangs during shutdown, a test suite never finishes, or a service keeps processing after it was told to stop. Interviewers like this question because the first half has a precise memory-model answer and the second half tests practical experience with blocking calls and interruption. In this answer, we will reproduce the problem, see why the JIT is allowed to cause it, fix it with volatile, and then look at the two cases where volatile alone is not enough.
1Reproducing the Problem
Here is the worker in full. One thread runs run(), and another thread calls stop() some time later.
It is tempting to think stop() eventually reaches memory and the loop eventually notices. Sometimes it does, especially when doWork() is large or calls methods the JIT cannot inline. But with a short loop body, a compiled loop commonly runs forever.
2Why the Loop Never Sees the Write
running is a plain field, and the two threads share it with no synchronization. In memory-model terms, there is no happens-before edge from the write in stop() to the reads in run(), so the JVM is not required to make the write visible to the worker at all.
The JIT uses that freedom. Looking only at the worker thread, nothing inside the loop writes running, and doWork() is inlined and clearly does not touch it. So the compiler may read the field once before the loop and keep the value in a register, which turns the loop into while (true). This optimization, hoisting a loop-invariant read, makes ordinary single-threaded loops faster, and it is exactly what breaks this one.
It often works in a short test because the loop is still interpreted, and the interpreter reads the field each time. Once the method is compiled after many iterations, the behaviour changes. That is why such bugs appear in long-running services and not in quick tests.
3The Fix: Declare running volatile
Marking the field volatile tells the JVM that other threads communicate through it.
Every volatile read must read the variable, so the JIT can no longer hoist it, and the volatile write in stop() happens-before every later read that sees it. The worker leaves the loop on its next check. volatile is enough here because the flag is a single independent value: nobody reads it, decides something and writes it back, and no invariant ties it to other fields. An AtomicBoolean would work equally well, but adds nothing for a plain flag.
4When volatile Is Not Enough: Blocking Work
The flag is only checked between calls to doWork(). If doWork() blocks, waiting on a queue, a socket, a lock or Thread.sleep, the worker might never return to the check. A consumer blocked in queue.take() on an empty queue will wait forever no matter what running says.
- stop() calledrunning = false, then
interrupt() - Worker inside doWork()?YesBlocked call throws or times outNoLoop checks running
- running is false?YesLeave the loop, clean upNoDo the next unit of work
3 steps in order. Play them, or step through them one at a time.
Interruption is Java's standard way to ask a blocked thread to stop waiting: blocking methods such as take(), sleep() and wait() throw InterruptedException when the thread is interrupted. A timed poll adds a second safety net, because the loop rechecks the flag at least once a second. For blocking I/O that does not respond to interrupts, such as a classic socket read, we use a read timeout or close the socket from stop(). And when the worker runs in an ExecutorService, shutdownNow() interrupts its threads for us.
5Publishing State When Stopping
Sometimes stopping must carry information, for example the reason or a final checkpoint the worker should save. Plain fields can carry it, as long as they are written before the volatile write. The volatile write then publishes them, by program order and transitivity: a worker that sees running as false also sees everything stop() wrote before it.
If the order were reversed, writing the reason after setting the flag, the worker could see running as false and still read a null reason. And if several threads may call stop() with different reasons, the plain field becomes a race between writers; then an AtomicReference or a lock is the better tool.
6Follow-up questions
Why not use Thread.interrupt() alone and drop the flag?
We can: while (!Thread.currentThread().isInterrupted()) is a valid loop condition. But interruption is easy to lose, because any code in doWork() that catches InterruptedException and ignores it clears the flag. Using both a volatile flag and interrupt is more robust: the flag records the intent permanently, and the interrupt wakes blocking calls.
Does making stop() synchronized fix it?
Only if run() also reads running under the same lock, for example through a synchronized isRunning() method. A synchronized writer with an unsynchronized reader still has no happens-before edge to the reader. volatile is simpler and cheaper for a single flag.
How long after stop() does the worker notice?
With volatile, it sees the new value on its next check, so the delay is at most the duration of one doWork() call. That is why long or blocking units of work need interruption or timeouts, which bound the delay.
7Conclusion
In this answer, we saw that a plain stop flag can be read once and cached by the JIT, so the worker never stops, and that declaring it volatile makes stop()'s write visible to the loop. volatile is enough for a single independent flag, but not when doWork() blocks, so we also interrupt the thread or use timed calls, and when stopping must publish more state, we write that state before the volatile write so the flag carries it along.
Open with
The field is a plain boolean, so there is no happens-before edge between the write in stop and the reads in run. Nothing in the loop writes running, so the JIT is allowed to read it once, keep it in a register and effectively turn the loop into while true.
Then, if they want more
That usually happens after the loop is compiled, which is why it works in quick tests and fails in a long-running service. The fix is to declare running volatile.
Every volatile read must actually read the variable, so the read cannot be hoisted, and the volatile write happens-before the read that sees false, so the worker leaves the loop on its next check. volatile is enough for the visibility of the flag, because it is a single independent value; nobody reads it and writes it back.
But it is not always enough to stop the worker. The flag is only checked between units of work, so if doWork blocks on a queue, a socket or a sleep, the worker never gets back to the check.
So in stop I would also interrupt the worker thread, handle InterruptedException in run by restoring the flag and exiting, and prefer timed calls like poll with a timeout, or socket timeouts for I/O that ignores interrupts.
If stopping has to pass extra state, like a reason, I write that state before the volatile write, so a worker that sees false also sees the reason.
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 "A worker loop is controlled by a stop flag:": https://scrivio-interview-library.netlify.app/java/java-memory-model/0599d34264/