2

在一次采访中,我被要求建议一个单例模式的设计/实现,我必须延迟加载类并且不使用同步关键字。我被噎住了,什么都想不出来。然后我开始阅读 java 并发和 concurrentHaspMap。请检查以下实施并确认您是否发现双重检查锁定的任何问题或此实施的任何其他问题。

package Singleton;

import java.util.concurrent.ConcurrentHashMap;

public final class SingletonMap {

    static String key = "SingletonMap";
    static ConcurrentHashMap<String, SingletonMap> singletonMap = new ConcurrentHashMap<String, SingletonMap>();
    //private constructor
    private SingletonMap(){

    }
    static SingletonMap getInstance(){

        SingletonMap map = singletonMap.get(key);       
        if (map == null){
                //SingletonMap newValue=  new SingletonMap();
                map =   singletonMap.putIfAbsent(key,new SingletonMap());
                if(map == null){
                    map = singletonMap.get(key);    
                }
        }       
        return map;
    }
}
4

2 回答 2

3

如果你知道怎么做就很简单

enum Singleton {
    INSTANCE;
}

是延迟加载和线程安全的INSTANCE(并且不使用任何类型的显式锁定)

于 2012-08-09T07:54:36.127 回答
2

另请参阅Bill Pugh 的解决方案

public class Singleton {
    // Private constructor prevents instantiation from other classes
    private Singleton() {}

    /**
     * SingletonHolder is loaded on the first execution of
     * Singleton.getInstance() or the first access to
     * SingletonHolder.INSTANCE, not before.
     */
    private static class SingletonHolder {
        public static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
于 2012-08-09T08:07:02.390 回答