I\'m reading about volatile keyword in Java and completely understand the theory part of it.
But, what I\'m searching for is, a good case example, which sho
What is volatile keyword ?
volatile keyword prevents
caching of variables.
Consider the code ,first without volatile keyword
class MyThread extends Thread {
private boolean running = true; //non-volatile keyword
public void run() {
while (running) {
System.out.println("hello");
}
}
public void shutdown() {
running = false;
}
}
public class Main {
public static void main(String[] args) {
MyThread obj = new MyThread();
obj.start();
Scanner input = new Scanner(System.in);
input.nextLine();
obj.shutdown();
}
}
Ideally,this program should print hello until RETURN key is pressed. But on some machines it may happen that variable running is cached and you cannot change its value from shutdown() method which results in infinite printing of hello text.
Thus using volatile keyword ,it is guaranteed that your variable will not be cached ,ie will run fine on all machines.
private volatile boolean running = true; //volatile keyword
Thus using volatile keyword is a good and safer programming practice.