Are you taking CLEP classes? Try clep.ai
| 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

Mark
< Prev
Next >

Consider the Java classes provided below. What concurrency issue arises from the declaration and use of the flag variable in the VisibilityDerived class?

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

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

B

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

C

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

D

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

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|