Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 2: Using Objects
Start Practice TestPractice Test
About Exam
hard

Java Volatile Keyword Purpose

Mark
< Prev
Next >

Which of the following best describes the purpose of declaring the stop variable as volatile in the provided code segment?

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 synchronizes method calls on the flag object to avoid race conditions.

C

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

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.

AI Tutor

How can I help?

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