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 shows what would happen if variable wasn't volatile and if it were.
Below code snippet doesn't work as expected (taken from here):
class Test extends Thread {
boolean keepRunning = true;
public void run() {
while (keepRunning) {
}
System.out.println("Thread terminated.");
}
public static void main(String[] args) throws InterruptedException {
Test t = new Test();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println("keepRunning set to false.");
}
}
Ideally, if keepRunning
wasn't volatile, thread should keep on running indefinitely. But, it does stop after few seconds.
I've got two basic questions:
- Can anyone explain volatile with example? Not with theory from JLS.
- Is volatile substitute for synchronization? Does it achieve atomicity?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…