Lazy初始化Singleton实现而不使用Synchronized Key字 [英] Lazy initialization of Singleton implementation without using Synchronized Key word

查看:144
本文介绍了Lazy初始化Singleton实现而不使用Synchronized Key字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在面试中被要求建议一个Singleton模式的设计/实现,其中我必须延迟加载类,也不使用同步关键字。我被窒息,无法想出任何东西。然后我开始阅读java并发和concurrentHaspMap。请检查以下内容,并确认您是否看到双重锁定或任何其他问题与此实施的任何问题。

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


推荐答案

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

这篇关于Lazy初始化Singleton实现而不使用Synchronized Key字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆