| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice Test
Share
hard Solved by 2 students
The Volatile Keyword in Multithreading
< Prev
Next >

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 guarantees atomic execution of the stop() method without the need for additional synchronization.

C

It synchronizes the access to the runTask() method, ensuring mutual exclusion.

D

It ensures that changes made to the ‘running’ flag in one thread are immediately visible to the other thread, preventing an infinite loop.

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

Question Leaderboard

Not enough data yet to show leaderboard.

APFIVE © 2020.
Email: [email protected]|Privacy Policy