Junior — Middle
Explain the concept of double-checked locking and how it is used to improve multithreading efficiency.
sobes.tech AI
Answer from AI
Double-Checked Locking is a pattern used to reduce synchronization overhead in a multithreaded environment. It is applied when you need to lazily initialize a resource (e.g., a singleton) and want to avoid unnecessary locking after the object has already been created.
The idea is to first check if the object is initialized without locking. If not, acquire the lock and check again to prevent race conditions, then create the object.
Example in Java:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // first check without locking
synchronized (Singleton.class) {
if (instance == null) { // second check with locking
instance = new Singleton();
}
}
}
return instance;
}
}
The key point is the use of volatile for the instance variable to ensure proper visibility of changes across threads.