Using volatile is yet another way (like synchronised, atomic wrapper) of making such a thread safe. Thread safe means that a method or class instance can be used by multiple threads at same time without any problem.
Ex:
public class VolatileExample extends Thread{
boolean isRunning = true;
public void run() {
while (isRunning) {
System.out.println("Hello");
try {
System.out.println("Started");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void shutdown() {
isRunning = false;
System.out.println("flag changes");
}
public static void main(String[] str) {
VolatileExample volatileExample = new VolatileExample();
volatileExample.start();
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
volatileExample.shutdown();
}
}
So we’ve two threads running here both are accessing the same variable. If one thread modifies its value then the change might not be reflect in the original one main memory instantly. This depends on write policy of cache. Now the other thread is not aware of modified value which leads to data inconsistency. Volatile is used to prevent the threads caching variables when they are not changed from within the thread.

Leave a comment