Effect of the Synchronized Keyword
Consider the SyncCheck class provided below. What is the effect of the synchronized keyword on the updateValue method?
public class SyncCheck {
private int value = 0;
public synchronized void updateValue(int newVal) {
if(newVal > value) {
value = newVal;
}
}
public int getValue() {
return value;
}
public static void main(String[] args) {
SyncCheck sc = new SyncCheck();
Runnable task = () -> { sc.updateValue((int)(Math.random()*100)); };
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}
A
It ensures that the if condition always evaluates to true, allowing safe updates.
B
It prevents deadlock by avoiding nested synchronization scenarios.
C
It ensures that only one thread can execute updateValue at a time, preventing concurrent race conditions.
D
It guarantees that the value’s read and update operations are inherently atomic even outside the method.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | hadleysmith5 | 1 | 1 | 0m 00s | 100 |
| #2 | kazvin.tjakradinata | 1 | 1 | 0m 18s | 82 |
| #3 | keithy.mcbeefy | 0 | 1 | 0m 58s | -68 |
Items per page:
10
1 – 3 of 3
APFIVE