Volatile
Explore the role of the volatile keyword in Java multi-threading to ensure that updates to variables by one thread are visible to others. Understand why marking variables as volatile can prevent visibility issues and when synchronization is not required for thread safety. This lesson enhances your grasp of concurrency concepts essential for Java programming and interview preparation.
We'll cover the following...
Explain the concept of volatile
Consider the class setup below:
class TaleOfTwoThreads {
boolean flag = true;
public void signalToStop() {
flag = false;
}
public void run() {
while (flag) {
// ... Run like crazy
}
}
}
When will the “All Done” statement be printed for the following snippet?
TaleOfTwoThreads example = new TaleOfTwoThreads();
// start runner thread
Thread runner = new Thread(() -> example.run());
runner.start();
// wait for one second before signalling to stop
Thread.sleep(1000);
Thread stopper = new Thread(() -> example.signalToStop());
stopper.start();
// wait for two threads to complete processing
stopper.join();
runner.join();
System.out.println("All Done");
Printed after approximately one second
An exception is thrown because we are not synchronizing access to the flag variable
May never be printed
May be printed after at least one second, or not at all, depending on JVM optimizations and memory visibility.
The answer may seem ...