Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice TestPractice Test
About Exam
hard Solved by 4 students

The Volatile Keyword in Multithreading

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Total Time
Score
#1busemagngr11 0m 28s 72
#2meromaroseif11 0m 32s 68
#3y.seong202712 2m 29s -59
Items per page:
10
1 – 3 of 3

AI Tutor

How can I help?

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