Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
hard

Java Thread Memory Visibility

Mark
< 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

Visibility is guaranteed because the thread was started after the main thread modified ‘flag’.

C

The worker thread might never observe the change to the ‘flag’ due to memory consistency errors, causing it to loop indefinitely.

D

The code may throw a runtime exception because of improper thread termination.

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.

AI Tutor

How can I help?

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