问题
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