| preferred AP College board partner for AP classes
AP Computer Science A/Unit 2: Using Objects
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Java Volatile Keyword Purpose
< Prev
Next >

What is the purpose of declaring the ‘stop’ variable as volatile in the above program?

public class Flag {
    public volatile boolean stop = false;
}

public class Worker extends Thread {
    private Flag flag;
    public Worker(Flag flag) { this.flag = flag; }
    public void run() {
         while (!flag.stop) { }
         System.out.println("Stopped");
    }
}

public class Main {
    public static void main(String[] args) {
        Flag flag = new Flag();
        Worker worker = new Worker(flag);
        worker.start();
        try { Thread.sleep(100); } catch(Exception e) {}
        flag.stop = true;
    }
}
A

It is unnecessary because all threads inherently see the latest value of shared variables.

B

It ensures that changes to ‘stop’ are visible across threads, preventing the worker thread from looping indefinitely.

C

It synchronizes method calls on the flag object to avoid race conditions.

D

It prevents the worker thread from being interrupted by ensuring the stop flag remains unchanged.

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