java中的单例模式。懒惰的初始化 [英] singleton pattern in java. lazy initialization

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

问题描述

public static MySingleton getInstance() {
 if (_instance==null) {
   synchronized (MySingleton.class) {
      _instance = new MySingleton();
   }
 }
 return _instance;
} 

1.上述getInstance方法的实现存在缺陷吗?
2.两种实现之间有什么区别。?

1.is there a flaw with the above implementation of the getInstance method? 2.What is the difference between the two implementations.?

public static synchronized MySingleton getInstance() { 
 if (_instance==null) {
  _instance = new MySingleton();
 }

 return _instance;
} 

我在stackoverflow中看到了很多关于单例模式的答案但是问题我发布的主要是知道在这种特殊情况下方法和块级别的'同步'的区别。

I have seen a lot of answers on the singleton pattern in stackoverflow but the question I have posted is to know mainly difference of 'synchronize' at method and block level in this particular case.

推荐答案


1.上述getInstance
方法的实现存在缺陷吗?

1.is there a flaw with the above implementation of the getInstance method?

它不起作用。你可以得到你的Singleton的几个实例。

It does not work. You can end up with several instances of your Singleton.


2.两个实现之间有什么区别。?

2.What is the difference between the two implementations.?

第二个工作,但需要同步,当你从不同的线程访问该方法时,这可能会减慢系统速度。

The second one works, but requires synchronization, which could slow down the system when you have a lot of accesses to the method from different threads.

最直接的正确实施:

public class MySingleton{
    private static final MySingleton _instance = new MySingleton();
    private MySingleton(){}
    public static MySingleton getInstance() { 
        return _instance;
    }
}

更短更好(安全可序列化):

Shorter and better (safely serializable):

public enum MySingleton{
    INSTANCE;

    // methods go here
}

延迟初始化单身人士是一个受到关注的主题方式与其实际实用性不成比例(IMO争论双重检查锁定的复杂性,你的例子是第一步,只不过是一个小便竞赛)。

Lazy initialization of singletons is a topic that gets attention way out of proportion with its actual practical usefulness (IMO arguing about the intricacies of double-checked locking, to which your example is the first step, is nothing but a pissing contest).

在99%的情况下,你根本不需要延迟初始化,或者Java的首次引用类时初始化就足够了。在剩下的1%的情况下,这是最好的解决方案:

In 99% of all cases, you don't need lazy initialization at all, or the "init when class is first referred" of Java is good enough. In the remaining 1% of cases, this is the best solution:

public enum MySingleton{
    private MySingleton(){}
    private static class Holder {
         static final MySingleton instance = new MySingleton();
    }
    static MySingleton getInstance() { return Holder.instance; }
}

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

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