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

The Volatile Keyword in Multithreading

< Prev
Next >

Consider the following Java program. What is the primary function of the volatile keyword as applied to the running instance variable?

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 ensures that changes made to the ‘running’ flag in one thread are immediately visible to the other thread, preventing an infinite loop.

B

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

C

It optimizes the loop by allowing swift iteration without memory overhead.

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

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