| preferred AP College board partner for AP classes
hard
Java Thread Memory Visibility
< Prev
Next >

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’.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy