Middle — Middle+
Explain the principle of the double-checked locking method in the context of multithreading.
sobes.tech AI
Answer from AI
The Double-Checked Locking method is used for lazy initialization of resources in a multithreaded environment to minimize synchronization overhead.
The idea is to first check if the resource is initialized without acquiring a lock (fast check). If the resource is not yet initialized, then a lock is acquired, and the check is repeated (second check) to prevent re-initialization if another thread has already done it.
Example in Java:
private volatile Resource resource;
public Resource getResource() {
if (resource == null) { // First check without lock
synchronized(this) {
if (resource == null) { // Second check with lock
resource = new Resource();
}
}
}
return resource;
}
The key point is the use of volatile for the variable to ensure visibility of changes across threads and to avoid instruction reordering issues.
Thus, locking is only used during the first initialization, and subsequent calls are lock-free, which improves performance.