Synchronization on String Literals
In the code below, the performAction method synchronizes on a String object. What is a potential pitfall of this approach?
public class ImmutableLock {
private final String lock = "LOCK";
public void performAction() {
synchronized(lock) {
System.out.println("Performing action");
}
}
}
A
The immutability of the String prevents race conditions, making synchronization unnecessary.
B
There is no pitfall; synchronizing on any object provides equivalent concurrency protection.
C
Synchronizing on immutable objects always ensures thread safety without any drawbacks.
D
Immutable objects like String can be interned and shared across the program, leading to unexpected contention or deadlocks if other parts synchronize on the same literal.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE