Java Thread Memory Visibility
Consider the FlagChecker class shown below. What is a potential issue if the flag instance variable is not declared as volatile?
public class FlagChecker {
private boolean flag = false;
public void runThread() {
new Thread(() -> {
while (!flag) {
// Busy waiting
}
System.out.println("Flag is true, proceeding.");
}).start();
}
public void setFlag() {
flag = true;
}
public static void main(String[] args) throws InterruptedException {
FlagChecker fc = new FlagChecker();
fc.runThread();
Thread.sleep(100);
fc.setFlag();
}
}
A
The flag variable will always remain false due to default boolean initialization.
B
The code may throw a runtime exception because of improper thread termination.
C
The worker thread might never observe the change to the ‘flag’ due to memory consistency errors, causing it to loop indefinitely.
D
Visibility is guaranteed because the thread was started after the main thread modified ‘flag’.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE