Why to double check the singleton instantiation

我的梦境 提交于 2019-12-12 04:55:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!