Video in progress
What is wrong with the following lazy Singleton, and how do you fix it?
public class TokenCache {
private static TokenCache instance;
private TokenCache() { loadFromDisk(); }
public static TokenCache getInstance() {
if (instance == null) {
instance = new TokenCache();
}
return instance;
}
}
Two threads can pass the instance == null check at the same time and create two objects. The fixes: the holder idiom, an enum, or double-checked locking with volatile.
📖 Answer
This is a classic race condition. Thread A sees null and enters the constructor. Before it finishes, Thread B also sees null. The result is two TokenCaches, the disk read twice, and somebody ends up working with the stale copy. In a local test this almost never shows up, but in prod under load it does.
The simplest fix is to make the method synchronized. It works, but every call takes the lock, even though it's only needed the first time.
A better one is the holder idiom:
public class TokenCache {
private TokenCache() { loadFromDisk(); }
private static class Holder {
static final TokenCache INSTANCE = new TokenCache();
}
public static TokenCache getInstance() {
return Holder.INSTANCE;
}
}
The Holder class is loaded only when getInstance() is first called, and the JVM performs class initialization thread-safely. You need neither a lock nor volatile.
If you write double-checked locking, the field must be volatile, otherwise another thread may see a half-constructed object.
Sign up to mark studied questions and save your progress.