Java Thread Race Condition
What potential concurrency issue exists in the code above?
public class Checker {
private int data = 0;
public void updateData() {
if(data == 0) {
data = 100;
}
}
public void printData() {
System.out.println(data);
}
public static void main(String[] args) {
Checker chk = new Checker();
Thread t1 = new Thread(() -> chk.updateData());
Thread t2 = new Thread(() -> chk.printData());
t1.start();
t2.start();
}
}
A
The data variable should be declared as final to prevent race conditions.
B
A deadlock might occur because printData() is not synchronized.
C
The if check and subsequent assignment in updateData() are not synchronized, which can lead to a race condition where printData() may read a stale or inconsistent value.
D
There is no issue because the unsynchronized read in printData() doesn’t impact the write in updateData().
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | mahmoudjibrin08 | 1 | 1 | 0m 00s | 100 |
| #2 | angelajxi11 | 1 | 1 | 0m 00s | 100 |
| #3 | mali.nehme | 0 | 1 | 0m 00s | -10 |
Items per page:
10
1 – 3 of 3
APFIVE