The volatile keyword in Java is used in multithreading to ensure that changes made to a variable by one thread are immediately visible to other threads.
When a variable is declared as volatile, the JVM reads it directly from main memory instead of thread cache.
// Declaring a volatile variable for thread visibility
public class SharedData {
volatile boolean running = true;
}
// Demonstrates how volatile ensures visibility between threads
class Worker extends Thread {
volatile boolean active = true;
public void run() {
while (active) {
}
System.out.println("Thread stopped");
}
public void stopWorker() {
active = false;
}
}
See how the volatile keyword affects data synchronization between Main Memory and Thread Cache.
When active is set to false from another thread, the running thread immediately detects the change and exits the loop.
volatile and observe inconsistent behaviorsynchronized keyword