Volatile variable in Java
In Java, the volatile keyword is used to indicate that a variable’s value will be modified by different threads. Declaring a variable as volatile ensures that its value is always read from and written to the main memory, making it visible to all threads. This keyword is used in multithreaded programming to avoid memory consistency errors.
Table of Contents
When a variable is declared as volatile
1. Visibility Guarantee: Changes to the variable are immediately visible to all threads. This means that a read of a volatile variable will always see the most recent write by any thread.
2. No Caching: Threads do not cache the value of the volatile variable. It ensures that the value is always read from and written to the main memory.
3. No Atomicity: The volatile keyword does not ensure atomicity. Operations on volatile variables are not atomic (e.g., increment operations).
Example
Below is an example demonstrating the use of a volatile variable in a multithreaded context.
java
class VolatileExample extends Thread {
private volatile boolean running = true;
public void run() {
while (running) {
System.out.println("Thread is running...");
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread stopped.");
}
public void stopRunning() {
running = false;
}
public static void main(String[] args) {
VolatileExample thread = new VolatileExample();
thread.start();
try {
Thread.sleep(2000); // Let the thread run for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stopRunning(); // This will stop the thread
System.out.println("Stop signal sent.");
}
}
Explanation:
Thread Definition
- VolatileExample class extends Thread and has a volatile boolean variable running.
- The run() method contains a loop that runs as long as running is true. It prints a message and sleeps for 500 milliseconds in each iteration.
Stopping the Thread
- The stopRunning() method sets the running variable to false.
- In the main method, a VolatileExample thread is started, which runs for 2 seconds.
- After 2 seconds, the stopRunning() method is called to stop the thread.
Volatile Keyword
- The volatile keyword ensures that changes to the running variable in the stopRunning() method are immediately visible to the thread running the run() method.
- Without volatile, the thread might cache the value of running and not see the update, causing it to continue running indefinitely.