Lesson 3 of 8
volatile & Memory Visibility
The Java Memory Model (JMM) allows threads to cache variables in CPU registers - so a write by one thread may not be visible to another. volatile guarantees visibility across threads. It's often misunderstood - it guarantees visibility but NOT atomicity.
volatile - Visibility vs Atomicity
public class VolatileDemo {
// ❌ Without volatile - JVM may cache 'running' in a CPU register
// Thread A reads cached 'true' even after Thread B writes 'false'
// Result: Thread A never stops - infinite loop!
static boolean running = true;
// ✅ With volatile - write by Thread B immediately visible to Thread A
static volatile boolean runningVolatile = true;
static volatile int sequenceNumber = 0;
// Safe stop pattern using volatile
public static class BackgroundTask implements Runnable {
private volatile boolean stopped = false;
public void stop() {
stopped = true; // write visible immediately to run() thread
}
@Override
public void run() {
while (!stopped) { // reads fresh value every iteration
// do work
try { Thread.sleep(10); } catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
System.out.println("Task stopped cleanly.");
}
}
// ⚠️ volatile is NOT atomic for compound operations
// volatile int counter = 0;
// counter++; // STILL a race condition! volatile only fixes visibility
// Use AtomicInteger for atomic compound operations
// volatile IS atomic for: reads and writes to primitive types (not long/double without volatile on 32-bit JVMs)
// volatile IS NOT atomic for: check-then-act, read-modify-write (counter++)
public static void main(String[] args) throws InterruptedException {
BackgroundTask task = new BackgroundTask();
Thread t = new Thread(task);
t.start();
Thread.sleep(500); // let task run for 500ms
task.stop(); // volatile write - visible immediately to t
t.join();
System.out.println("Main done.");
}
}Quick Quiz
Tip
Tip
Practice volatile Memory Visibility in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for volatile & Memory Visibility
Practice Task
Note
Practice Task - (1) Write a working example of volatile Memory Visibility from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with volatile Memory Visibility is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?