Concurrency and Static Method Hiding
In the code below, the UnsafeCounter class defines an increment method that hides the synchronized static method from the Counter superclass. What is the primary concurrency issue that arises from this design?
class Counter {
public static int total = 0;
public static synchronized void increment() {
total++;
}
}
class UnsafeCounter extends Counter {
public static void increment() {
// Overridden without synchronization
total++;
}
}
public class StaticTest extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
UnsafeCounter.increment();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new StaticTest();
Thread t2 = new StaticTest();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Total: " + UnsafeCounter.total);
}
}
A
It causes a compile-time error since static methods cannot be overridden.
B
It improves performance with proper thread safety due to static fields.
C
It creates a deadlock because static methods require class-level locking.
D
It removes the synchronization, enabling race conditions on the static variable ‘total’.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE