Introduction
In Java, multithreading allows multiple threads to execute concurrently, improving application performance and responsiveness. However, when multiple threads share variables, maintaining data consistency becomes a challenge. Due to CPU caching and compiler optimizations, one thread may not immediately see updates made by another thread, leading to unexpected behavior.
To solve this visibility problem, Java provides the volatile keyword. A variable declared as volatile ensures that every read operation retrieves the latest value from the main memory and every write operation is immediately visible to all threads.
Although volatile improves visibility, it is not a replacement for synchronization. It does not provide mutual exclusion or make compound operations such as increment (count++) atomic.
What is the Java Volatile Keyword?
The volatile keyword is a modifier that tells the Java Virtual Machine (JVM) that the value of a variable may be modified by multiple threads.
When a variable is declared as volatile:
- Every write is immediately written to the main memory.
- Every read fetches the latest value from the main memory.
- Changes made by one thread become visible to all other threads without unnecessary delay.
In simple terms, volatile guarantees visibility of shared variables across threads.
Why is volatile Needed?
Modern processors use CPU caches to improve performance. Each thread may read a variable into its local cache.
Consider the following situation:
- Thread A changes a variable.
- The new value remains only in Thread A’s cache.
- Thread B continues reading the old cached value.
- Both threads now have inconsistent data.
The volatile keyword prevents this problem by ensuring that reads and writes happen directly with the main memory.
Syntax
Declaring a volatile variable is simple.
volatile int count;
Or while initializing:
private volatile boolean running = true;
The keyword is placed before the variable’s data type.
How volatile Works
Normally:
Thread A
↓
CPU Cache
Thread B
↓
CPU Cache
Each thread may use its own cached value.
With volatile:
Thread A
↓
Main Memory
↑
Thread B
Every thread communicates with the main memory, ensuring that all threads observe the latest value.
Example Without volatile
class Demo {
boolean running = true;
void stop() {
running = false;
}
void execute() {
while(running) {
}
System.out.println("Stopped");
}
}
The execute() method may never stop because another thread’s update to running might not become visible.
Example With volatile
class Demo {
voatile boolean running = true;
void stop() {
running = false;
}
void execute() {
while(running) {
}
System.out.println("Stopped");
}
}
Now, when another thread changes running to false, the executing thread immediately sees the updated value and exits the loop.
Example: Thread Communication
class Worker extends Thread {
private volatile boolean running = true
public void run() {
while(running) {
System.out.println("Working...");
}
System.out.println("Stopped");
}
public void stopThread() {
running = false;
}
}
public class Demo {
public static void main(String[] args) throws Exception {
Worker worker = new Worker();
worker.start();
Thread.sleep("1110");
worker.stopThread()
}
}
Output
Working…
Working…
Stopped
The volatile keyword ensures that the worker thread notices the updated value of running.
What volatile Guarantees
The volatile keyword provides two important guarantees.
1. Visibility
Every thread always reads the latest value from the main memory.
Example:
volatile boolean finished;
If one thread sets:
finished = true;
All other threads immediately see the updated value.
2. Ordering (Happens-Before Relationship)
Writes to a volatile variable establish a happens-before relationship with subsequent reads of that same variable.
This prevents certain instruction reordering by the compiler and processor around the volatile access, helping ensure predictable visibility between threads.
What volatile Does NOT Guarantee
Many beginners misunderstand the purpose of volatile.
It does not provide:
- Mutual exclusion
- Thread synchronization
- Atomic operations
- Locking
- Protection against race conditions involving compound actions
Example:
volatile int count = 0;
count++;
The increment operation involves multiple steps:
- Read the value.
- Increase it.
- Write it back.
If multiple threads execute this simultaneously, updates can still be lost.
volatile vs synchronized
| Feature | volatile | synchronized |
|---|---|---|
| Visibility | Yes | Yes |
| Atomicity | No | Yes (for code within the synchronized block) |
| Lock Required | No | Yes |
| Performance | Generally faster | Slower due to locking overhead |
| Prevents Race Conditions | No | Yes, when used correctly |
| Use Case | Status flags, configuration values | Shared mutable data requiring compound operations |
volatile vs Atomic Variables
| Feature | volatile | Atomic Variable |
|---|---|---|
| Visibility | Yes | Yes |
| Atomic Operations | No | Yes |
| Locking | No | No |
| Package | Language keyword | java.util.concurrent.atomic |
| Best For | Shared flags | Counters and atomic updates |
For counters or increment operations, classes such as AtomicInteger are usually a better choice than a volatile integer.
Real-Life Example
Imagine a traffic signal.
- The traffic controller changes the light from Red to Green.
- Every driver immediately sees the updated signal.
- Nobody continues driving based on an outdated light.
This is similar to a volatile variable.
- Signal = shared variable
- Drivers = threads
- Traffic controller = thread updating the variable
- Immediate visibility = volatile
Common Use Cases
The volatile keyword is commonly used for:
- Stop flags
- Shutdown signals
- Configuration values
- Feature toggles
- Application state flags
- Initialization status indicators
- Simple thread communication
Common Mistakes
1. Using volatile for Counters
Incorrect:
volatile int count;
count++;
The increment is not atomic.
Use an AtomicInteger or synchronization instead.
2. Assuming volatile Prevents Race Conditions
volatile only guarantees visibility.
It does not prevent multiple threads from modifying a value simultaneously.
3. Using volatile for Complex Objects
Declaring an object reference as volatile ensures visibility of the reference itself, but it does not automatically make all modifications to the object’s internal mutable state thread-safe.
4. Replacing synchronized with volatile
If multiple operations must execute as one indivisible unit, volatile is not sufficient.
Use synchronization or other concurrency mechanisms.
5. Overusing volatile
Not every shared variable needs to be volatile.
Use it only when visibility is required without compound updates.
Best Practices
- Use volatile for simple shared flags and state variables.
- Do not use volatile for compound operations such as incrementing counters.
- Prefer AtomicInteger, AtomicBoolean, or other atomic classes for atomic updates without locking.
- Use synchronized or locks when multiple operations must execute atomically.
- Keep shared mutable state to a minimum.
- Understand the difference between visibility and atomicity before choosing volatile.
Conclusion
The Java volatile keyword is an important feature for multithreaded programming. It guarantees that changes made to a shared variable are immediately visible to all threads and establishes a happens-before relationship for reads and writes of that variable.
However, volatile is not a substitute for synchronization. It does not provide atomicity or protect against race conditions involving compound operations. For simple flags and state variables, volatile is an excellent choice because it avoids the overhead of locking while ensuring visibility. For more complex shared data, synchronization or atomic classes should be used.