| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice TestPractice Test
About Exam
hard Solved by 8 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 ensures that changes made to the ‘running’ flag in one thread are immediately visible to the other thread, preventing an infinite loop.

C

It guarantees atomic execution of the stop() method without the need for additional synchronization.

D

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

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: [email protected]|Privacy Policy