Java Volatile Keyword Purpose
What is the purpose of declaring the ‘stop’ variable as volatile in the above program?
public class Flag {
public volatile boolean stop = false;
}
public class Worker extends Thread {
private Flag flag;
public Worker(Flag flag) { this.flag = flag; }
public void run() {
while (!flag.stop) { }
System.out.println("Stopped");
}
}
public class Main {
public static void main(String[] args) {
Flag flag = new Flag();
Worker worker = new Worker(flag);
worker.start();
try { Thread.sleep(100); } catch(Exception e) {}
flag.stop = true;
}
}
A
It is unnecessary because all threads inherently see the latest value of shared variables.
B
It ensures that changes to ‘stop’ are visible across threads, preventing the worker thread from looping indefinitely.
C
It synchronizes method calls on the flag object to avoid race conditions.
D
It prevents the worker thread from being interrupted by ensuring the stop flag remains unchanged.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE