Category: java
What volatile Means
Published on 27 Oct 2026
Explanation
volatile makes writes to a variable visible to other threads that subsequently read it. It also imposes ordering guarantees. It does not make compound operations such as count++ atomic.
Code:
public class VolatileDemo {
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (running) { /* do work */ }
System.out.println("Stopped");
});
worker.start();
Thread.sleep(100);
running = false;
worker.join();
}
}
Explanation
A volatile boolean is useful for a simple stop flag because one thread's update becomes visible to another thread reading the flag. Use interruption or higher-level concurrency tools when they better fit the task.
Code:
public class StopFlagDemo {
private volatile boolean active = true;
public void stop() { active = false; }
public void runTask() {
while (active) { /* perform a small unit of work */ }
}
}
Explanation
Even if count is volatile, count++ remains a non-atomic read-modify-write sequence. Multiple threads can still lose updates. Use AtomicInteger or synchronization when updates must not be lost.
Code:
public class VolatileCounterWarning {
private volatile int count;
public void increment() { count++; } // Not atomic
public int getCount() { return count; }
}
Explanation
A write to a volatile variable happens-before a subsequent read of that same variable. This can safely publish a simple state flag, but it does not automatically make every other shared field safe for arbitrary concurrent updates.
Code:
public class PublicationDemo {
private static int data;
private static volatile boolean ready;
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
while (!ready) { Thread.yield(); }
System.out.println(data);
});
reader.start();
data = 42;
ready = true;
reader.join();
}
}
Explanation
Use volatile for simple state visibility, such as a shutdown flag or a safely published reference with suitable design. Prefer synchronized, locks, atomic classes, or concurrent utilities when multiple operations must be coordinated as one unit.
Code:
import java.util.concurrent.atomic.AtomicBoolean;
public class ShutdownSignal {
private final AtomicBoolean stopped = new AtomicBoolean();
public void stop() { stopped.set(true); }
public boolean isStopped() { return stopped.get(); }
}