← Back to Chapters

volatile Keyword in Java

⚡ volatile Keyword in Java

? Quick Overview

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.

? Key Concepts

  • Ensures visibility of shared variables across threads
  • Prevents thread-local caching of variables
  • Does not provide atomicity
  • Mainly used in low-level concurrency control

? Syntax / Theory

When a variable is declared as volatile, the JVM reads it directly from main memory instead of thread cache.

? View Code Example
// Declaring a volatile variable for thread visibility
public class SharedData {
volatile boolean running = true;
}

? Code Example(s)

? View Code Example
// 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;
}
}

? Interactive Simulation

See how the volatile keyword affects data synchronization between Main Memory and Thread Cache.

 

? Main Memory (RAM)

active = true
Source of Truth
↔️
Sync Status

⚡ Thread 1 (Cache)

active = true
⚙️ Running...
System Ready: Press "Set active = false" to test visibility.

? Live Output / Explanation

Explanation

When active is set to false from another thread, the running thread immediately detects the change and exits the loop.

✅ Tips & Best Practices

  • Use volatile only for flags or state indicators
  • Do not use it when atomic operations are required
  • Combine with synchronization if compound actions are involved

? Try It Yourself

  • Create two threads sharing a volatile variable
  • Remove volatile and observe inconsistent behavior
  • Compare with synchronized keyword