在不使用同步关键字的情况下,懒惰初始化Singleton实现

时间:2012-08-09 07:49:24

标签: java concurrency singleton synchronized

我在接受采访时被问到建议单一模式的设计/实现,我必须懒惰加载类,也不使用同步关键字。我被ch咽了,无法想出任何东西。然后我开始阅读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;
    }
}

2 个答案:

答案 0 :(得分:3)

如果你知道如何

,这很简单
enum Singleton {
    INSTANCE;
}

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

答案 1 :(得分:1)

另见Bill Pugh's solution

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;
    }
}