Volatile Variable Shadowing and Concurrency
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.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE