Junior — Middle
What is the purpose of the double-checked locking mechanism in multithreaded programming?
sobes.tech AI
Answer from AI
The Double-Checked Locking mechanism is used to optimize thread-safe resource initialization, such as a singleton. The idea is to avoid unnecessary synchronization after the object has already been created.
First, it checks whether the object is initialized without locking (fast check). If not, synchronization occurs, and a second check is performed to ensure that another thread hasn't created the object in the meantime. If the object is still not created, it is initialized.
Example in Java:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // first check without lock
synchronized (Singleton.class) {
if (instance == null) { // second check with lock
instance = new Singleton();
}
}
}
return instance;
}
}
The key point is the use of volatile for the instance variable to avoid visibility and instruction reordering issues.