Java中的单例设计模式 [英] Singleton Design Pattern in Java

查看:80
本文介绍了Java中的单例设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Singleton中的双锁检查通常写为:

Double Lock check in Singleton is generally written as :

public static Singleton getInstance()
{ 
    if (instance == null)
    {
        synchronized(Singleton.class) {  //1
            if (instance == null)          //2
                  instance = new Singleton();  //3
        }
    }
    return instance; //4
} 

在上面的代码中,假设有十个线程正在调用此方法,所有线程都超过了第一个if条件,然后一个线程进入了同步块并创建了实例.即使创建了实例,剩下的9个线程也将一一出现,它们需要等待并依次通过同步块.我希望任何线程一旦创建Singleton实例,其他所有线程都不应等待.告诉我是否有解决方案?

In the code above, suppose ten threads are calling this method, all of them crossed the first if condition, then one thread enters into the synchronized block and creates the instances. Remaining 9 thread would come one by one even if the instance is created they need to wait and come in sequence through the synchronized block. I want that as soon as any of the threads creates the Singleton instance all the other threads should not wait. Tell me if there is some solution for this?

推荐答案

如果您坚持使用惰性实例化,我认为没有解决方案.您可以在声明时创建单例对象instance变量:

I don't think there's a solution if you insist on using lazy instantiation. You could just create your singleton object when you declare the instance variable:

class Singleton {
    private static final instance = new Singleton();

    private Singleton() {} // prevent outside construction

    public static Singleton getInstance() {
        return instance; // no synchronization needed
    }
}

感谢eSniff的评论(以及yair的评论使我对eSniff的评论正确),这是在维基百科获取线程安全和惰性的方法:

Thanks to the comment by eSniff (and the comment by yair to set me right about eSniff's comment), here's the method posted in Wikipedia for a thread-safe and lazy method:

class Singleton {
    private static class Holder {
        static final instance = new Singleton();
    }

    private Singleton() {} // prevent outside construction

    public static Singleton getInstance() {
        return Holder.instance; // no synchronization needed
    }
}

这篇关于Java中的单例设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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