辛格尔顿执行的初始化工作,而无需使用同步关键词(Lazy initialization of Sin

2019-09-21 01:32发布

有人问我,在接受采访时提出一个设计/实施Singleton模式在那里我有懒加载类,也不能使用synchronized关键字。 我得到了哽咽,不能拿出anything.I然后我开始阅读关于Java并发和concurrentHaspMap。 请检查下面的imlpementation,如果你看到任何问题与仔细检查锁定或与此实现的任何其他问题可否证实。

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

Answer 1:

又见比尔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;
    }
}


Answer 2:

它很简单,如果你知道如何

enum Singleton {
    INSTANCE;
}

INSTANCE是懒加载和线程安全的(和不使用任何形式的显式锁定)



文章来源: Lazy initialization of Singleton implementation without using Synchronized Key word