Which kind of Singleton is this?

隐身守侯 提交于 2019-12-10 12:29:21

问题


public class ConnectionManager {

    private static Map <String, ConnectionManager> managerInstances = new HashMap<String, ConnectionManager>();

    private String dsKey;
    private ConnectionManager(String dsKey){
        this.dsKey = dsKey;
    }

    public static ConnectionManager getInstance(String dsKey){
        ConnectionManager managerInstance = managerInstances.get(dsKey);

        if (managerInstance == null) {
            synchronized (ConnectionManager.class) {
                managerInstance = managerInstances.get(dsKey);
                if (managerInstance == null) {
                    managerInstance = new ConnectionManager(dsKey);
                    managerInstances.put(dsKey, managerInstance);
                }
            }
        }
        return managerInstance;
    }
}

I recently saw this code somewhere where the Singleton pattern was not used as per book definition from GoF. Singleton is storing a Map of its own instances.

What kind of singleton can this be called? Or is this a valid use of Singleton?


回答1:


It's not a singleton. It's called multiton pattern.

Rather than have a single instance per application, the multiton pattern instead ensures a single instance per key.




回答2:


That multiton seems broken as it uses a double-checked locking idiom which is not thread safe in Java. In particular, when calling getInstance(s), with s a non-null String, you could receive a non-null reference pointing to a ConnectionManager whose dsKey is null.

It would be much better to use a thread safe ConcurrentHashMap instead and remove the need for synchronization.



来源:https://stackoverflow.com/questions/18119217/which-kind-of-singleton-is-this

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