问题
In this link i found the singleton instantiation as below:
public static Singleton getInstanceDC() {
if (_instance == null) { // Single Checked (1)
synchronized (Singleton.class) {
if (_instance == null) { // Double checked
_instance = new Singleton();
}
}
}
return _instance;
}
I am not getting the point of single check ie (1) . Whats its use here any way the single thread will be checking the instance inside synchronized block , so what is point of using the first check?
回答1:
Consider that in a multithreaded environment two threads can access your singleton. Here is what can happen without a double check.
First thread enters getInstanceDC()
; _instance
is null
so it enters the if
block.
Second thread enters getInstanceDC()
; _instance
is null
so it enters the if
block.
First thread creates a new instance.
Second thread creates a new instance.
The double check in a synchronized block solves this problem.
So why not synchronize the whole method? The answer is for performance reasons.
来源:https://stackoverflow.com/questions/29082448/why-to-double-check-the-singleton-instantiation