| preferred AP College board partner for AP classes
AP Computer Science A/Unit 9: Inheritance
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Volatile Variable Shadowing and Concurrency
< Prev
Next >

What concurrency issue arises from the way VisibilityDerived handles the ‘flag’ variable?

class VisibilityBase {
    protected volatile boolean flag = false;
    public void toggle() {
        flag = !flag;
    }
}

class VisibilityDerived extends VisibilityBase implements Runnable {
    // Shadowing the volatile flag
    public boolean flag = true;
    
    @Override
    public void toggle() {
        flag = !flag;
    }
    
    public void run() {
        for (int i = 0; i < 1000; i++) {
            toggle();
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        VisibilityDerived vd = new VisibilityDerived();
        Thread t1 = new Thread(vd);
        Thread t2 = new Thread(vd);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Flag: " + vd.flag);
    }
}
A

There is no concurrency problem because the toggle() method is repeatedly called, ensuring visibility.

B

A deadlock occurs because volatile variables cannot be shadowed in a subclass.

C

The program will not compile because of conflicting declarations of ‘flag’.

D

Shadowing the volatile flag causes the overridden toggle() method to update a non-volatile variable, leading to potential visibility and race condition issues.

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