Lazy initialization of Singleton implementation without using Synchronized Key word

蹲街弑〆低调 提交于 2019-12-24 02:05:50

问题


I was asked in an interview to suggest a design/implementation of a Singleton Pattern where I have to Lazy load the class and also not use the synchronized key word. I got choked and could not come up with anything.I then I started reading on java concurrency and concurrentHaspMap. Please check the below imlpementation and kindly confirm if you see any issue with Double check Locking or any other issues with this implementation.

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

回答1:


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



回答2:


Its pretty simple if you know how

enum Singleton {
    INSTANCE;
}

The INSTANCE is lazy loaded and thread safe (and doesn't use explict locking of any kind)



来源:https://stackoverflow.com/questions/11878926/lazy-initialization-of-singleton-implementation-without-using-synchronized-key-w

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