Concurrency Risk With Compound Conditions
Consider the following ConditionCheck class. What is the primary concurrency risk associated with the compound boolean expression in the useResource method?
public class ConditionCheck {
private int resource = 0;
public void useResource() {
if (resource > 0 && resource < 100) {
resource += 10;
System.out.println("Resource updated: " + resource);
}
}
public void setResource(int value) {
resource = value;
}
public static void main(String[] args) {
ConditionCheck cc = new ConditionCheck();
Thread t1 = new Thread(() -> {
for(int i = 0; i < 10; i++){
cc.useResource();
}
});
Thread t2 = new Thread(() -> cc.setResource(50));
t1.start();
t2.start();
}
}
A
The use of the && operator provides thread safety, so there is no concurrency issue.
B
A deadlock will occur because checking two conditions simultaneously locks the resource indefinitely.
C
The compound condition always evaluates to true, so it introduces no risk.
D
The evaluation of the compound condition and the subsequent update are not atomic, leading to potential race conditions when multiple threads access ‘resource’.
Question Leaderboard
Not enough data yet to show leaderboard.
