skip to content

Do Thread.sleep and Thread.yield have memory effects, and why can a loop polling a plain field with sleep() never see the update?

level: middleimportance: should knowfreq 52%

answer

  1. scheduling is not synchronization
  2. cached reads across a call
  3. no happens-before edge from the writer
  4. permitted by the JLS, rare on HotSpot

basics

~20 s

Thread.sleep and Thread.yield have no synchronization semantics in the JLS, so the compiler may read a non-volatile field once and reuse that value, and a polling loop may never end. Use a volatile field or a blocking hand-off.

solid answer

~40 s

No. JLS 17.3 says neither `Thread.sleep` nor `Thread.yield` has any synchronization semantics: the compiler need not flush cached writes before the call or reload cached values after it. So with a non-volatile `done`, `while (!done) Thread.sleep(1000);` may read the field once and reuse that value, and the loop need never terminate. Nothing orders the writer's write before those reads, which is a data race. On HotSpot at JDK 27 the sleeping loop usually does exit soon after the write, so the bug passes tests, while `while (!done) {}` keeps looping at default settings; neither outcome is promised. Even when the new `done` shows up, other fields written before it are not promised. Declare the field `volatile`, or better, replace polling with a blocking hand-off such as `CountDownLatch`, whose `countDown` happens-before a return from `await`.

code

java · 17 lines
java
public class StaleFlag {
    static boolean done; // not volatile: this is the bug

    public static void main(String[] args) throws InterruptedException {
        Thread poller = new Thread(() -> {
            while (!done) {
                // an empty body: the loop does nothing but read done
            }
        });
        poller.setDaemon(true);
        poller.start();
        Thread.sleep(2000);
        done = true;
        poller.join(3000);
        System.out.println(poller.isAlive() ? "still polling" : "poller exited");
    }
}

go deeper

for a junior

Recall that Thread.sleep and Thread.yield do not make other threads' writes visible. A flag shared between threads needs volatile or another proper hand-off, however long the loop sleeps.

for a middle

Explain JLS 17.3 in terms of happens-before: no edge from the writer, so the compiler may keep reusing one read of a plain field. Name the edges that do exist: volatile, monitors, start, join and interrupt.

for a senior

Say plainly that a sleeping poll usually exits on HotSpot, and that this hides a data race and does not disprove it. In review, look for plain flags guarding other data, because stale data is the failure that reaches production.

for a principal

Weigh a team rule against polling with sleep at all: a blocking hand-off removes both the data race and the wake-up latency. Review has to catch this, because passing tests say little about a data race.

## What the specification says `Thread.sleep` pauses the current thread for a given time, and `Thread.yield` hints that the thread is willing to give up its processor. Neither is a way for threads to communicate. JLS §17.3 says it directly: "neither `Thread.sleep` nor `Thread.yield` have any synchronization semantics". It spells out both directions: - **Before the call**, the compiler does not have to flush writes cached in registers out to shared memory. - **After the call**, the compiler does not have to reload values cached in registers. In that chapter, "compiler" means anything that can reorder code, which includes a JIT compiler and the processor. The term to know is **happens-before**. A write is guaranteed to be visible to a read in another thread only if the write happens-before the read. A write and a read of the same field in different threads with no such ordering form a **data race**. Synchronization semantics are what create those orderings, so a call without them adds none. ## Why the polling loop may never end This is the JLS's own example, with `this.done` a non-volatile `boolean`: ```java while (!this.done) Thread.sleep(1000); ``` The specification says the compiler "is free to read the field `this.done` just once, and reuse the cached value in each execution of the loop", in which case the loop never terminates, even after another thread changes the field. The reasoning runs like this: - The polling thread never writes `done`, so within that thread a single read looks the same as many. - The other thread's write is not ordered against those reads, so nothing requires them to return it. - The pause adds no ordering, whatever its length. A longer sleep gives more time, not a guarantee. ## What HotSpot does today What the language permits and what one JVM does are different things: | Loop on a non-volatile `done` | Usual result on HotSpot, JDK 27 and 25 | Promised by the JLS? | |---|---|---| | `while (!done) {}` | keeps looping at default settings; exits under `-Xint` | no | | `while (!done) Thread.sleep(1000);` | exits at its next wake-up after the write | no | | `while (!done) Thread.yield();` | exits soon after the write | no | | any of these with `volatile boolean done` | exits | yes: a later read must see that write or a later one | Which of these loops exits is the JVM's behaviour, not a rule: the JLS lets every one of them keep reusing its first read, so the sleeping loop passes its tests while the code stays incorrect. Run the empty loop with and without `-Xint` to see one program give both outcomes. Section 17.3 also makes no exception for virtual threads, where the calls take a different internal path. ## The second failure: a fresh flag publishes nothing else Even when the new `done` does show up, a plain flag says nothing about other fields. Take a writer running `result = compute(); done = true;` and a reader that leaves its loop and uses `result`. With no happens-before edge, the reader can see `done` as `true` and still read an old `result`. JLS §17.4.5 says writes in a data race "may, for example, appear to occur out of order" to those reads. A loop that always exits can still hand over stale data. Make `done` volatile and the write to `result` happens-before the read of `result` that follows seeing `true`. ## What does create an edge | Action | Ordered before | |---|---| | `Thread.sleep`, `Thread.yield` | nothing | | write to a `volatile` field | every subsequent read of that field | | unlock of a monitor | every subsequent lock of that monitor | | `Thread.start()` | every action in the started thread | | all actions in a thread | another thread's successful return from `join()` on it | | `interrupt()` | the point where the interruption is detected, including a thrown `InterruptedException` | | `CountDownLatch.countDown()` | a successful return from `await()` on that latch in another thread | The `interrupt()` row is the one edge near a sleep: a `Thread.sleep` that ends in `InterruptedException` does carry an ordering, but it comes from the `interrupt()` call, not from sleeping. How to handle that exception, and how a `synchronized` pair fixes a stale flag, are covered with thread interruption and with `synchronized`'s memory effects. ## Fixing the loop - **`volatile boolean done`.** The smallest fix. It gives the read its edge, and earlier writes by the writer come along. The poller can still wait up to one full sleep after the flag flips. - **`AtomicBoolean`.** Its `get` and `set` have volatile memory effects, and it adds `compareAndSet` when several threads may flip the flag. - **A blocking hand-off.** When one thread waits for another, `CountDownLatch.await()`, `Thread.join()` or `Future.get()` wake it without polling and carry the edge themselves. `Thread.onSpinWait()` is not a fix either: it is a hint for busy-wait loops, and the example in its own documentation polls a `volatile` field.

  • Does a thread that writes a plain flag and then calls Thread.sleep publish that write to other threads?
    Not through that call. JLS 17.3 says the compiler does not have to flush writes cached in registers before `Thread.sleep` or `Thread.yield`. Another thread may or may not see the value, because the write and its read still form a data race. To publish it, write a `volatile` field or leave a monitor the reader later enters.
  • If the polling loop does see done become true, can it trust the other plain fields the writer set first?
    No. Seeing the new value of a plain field creates no happens-before edge, so other writes may appear out of order to this reader, and `result` can still read old. With a `volatile` `done`, the write happens-before any read that follows it, so everything the writer did before setting it is visible once the reader sees `true`.
  • Which of the Thread class's own coordination calls do carry memory effects?
    `Thread.start()` happens-before every action in the started thread. All actions in a thread happen-before another thread's successful return from `join()` on it, and detecting termination through `isAlive()` gives the same ordering. `interrupt()` synchronizes-with the point where the interruption is detected, including a thrown `InterruptedException`. `sleep` and `yield` add nothing of their own.

Napping between glances at your own photocopy of a notice does not update the photocopy. Only an agreement that sends you back to the board after the poster has changed it does.

  • Thread.sleep flushes cached values, so a polling loop will always see the new field value.
  • A context switch during sleep forces a re-read of shared memory, so volatile is unnecessary.
  • Thread.yield acts as a memory barrier because it hands the processor to the writing thread.
  • A flag with only one writer needs no volatile for its readers to see the change.
  • The polling loop passed every run on my machine, so the code is correct.
  • A longer sleep between polls guarantees that the update has become visible.

Thread.sleep and Thread.yield
Java 1.0
Java Memory Model happens-before (JSR 133)
Java 1.5
CountDownLatch
Java 1.5

Assumes Java 27: the rule is JLS 17.3 for Java SE 27, and the HotSpot behaviour described, the same on JDK 25, is what the JVM does and not what the language promises.

context