Fundamentals 3 min read

Why a Volatile Boolean Won’t Stop a Java Thread Loop – and What Actually Works

This article explains why a non‑volatile boolean flag cannot reliably break a Java thread’s infinite loop, details the visibility and reordering issues that volatile solves, and presents correct solutions such as using volatile or AtomicBoolean for safe loop termination.

JavaEdge
JavaEdge
JavaEdge
Why a Volatile Boolean Won’t Stop a Java Thread Loop – and What Actually Works

Interview Question

A thread runs an infinite loop controlled by a boolean flag that is initially true. After some time the main thread sets the flag to false. The question is whether the child thread can exit if the flag is not declared volatile.

Principle

The volatile keyword addresses two core problems: visibility and instruction‑reordering. Visibility means the CPU cache must be invalidated so that a thread reads the latest value from main memory. Reordering prevention on x86 is implemented as a store‑load memory barrier (the “happen‑before” rule). The underlying mechanism uses the esp register. Without volatile, the cached value may never be refreshed, so the loop may never notice the change.

Solution

Declare the flag as volatile to force a write‑through to main memory and guarantee that other threads see the updated value, allowing the loop to terminate. Even inserting a System.out.println inside the loop works because the method is synchronized, which flushes the working memory. A more robust alternative is to use AtomicBoolean or AtomicReference, which not only ensure visibility but also provide atomic compare‑and‑set operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyThreadvolatileAtomicBoolean
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.