The Volatile Keyword in Multithreading
What role does the volatile keyword play for the ‘running’ flag in this program?
public class VolatileFlag {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void runTask() {
while(running) {
// perform some task
}
System.out.println("Stopped");
}
public static void main(String[] args) throws InterruptedException {
VolatileFlag vf = new VolatileFlag();
Thread t = new Thread(() -> vf.runTask());
t.start();
Thread.sleep(100);
vf.stop();
}
}
A
It optimizes the loop by allowing swift iteration without memory overhead.
B
It ensures that changes made to the ‘running’ flag in one thread are immediately visible to the other thread, preventing an infinite loop.
C
It guarantees atomic execution of the stop() method without the need for additional synchronization.
D
It synchronizes the access to the runTask() method, ensuring mutual exclusion.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE