Static Synchronized Method Behavior
What does the use of the ‘static synchronized’ keyword in the increment() method ensure in this example?
public class StaticInstanceSync {
private static int counter = 0;
public static synchronized void increment() {
counter++;
}
public void runTask() {
for(int i = 0; i < 1000; i++) {
increment();
}
}
public static void main(String[] args) throws InterruptedException {
StaticInstanceSync sis1 = new StaticInstanceSync();
StaticInstanceSync sis2 = new StaticInstanceSync();
Thread t1 = new Thread(() -> sis1.runTask());
Thread t2 = new Thread(() -> sis2.runTask());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter);
}
}
A
It ensures that only one thread, across all instances, executes the increment() method at a time, preventing race conditions on the counter variable.
B
It guarantees atomic updates to the counter variable without any performance cost.
C
It mistakenly synchronizes on the instance lock, rendering the static method non-thread-safe.
D
It only synchronizes threads accessing the same instance, so race conditions may occur between different instances.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE