Singleton with Enum vs Singleton with double-checked locking [英] Singleton with Enum vs Singleton with double-checked locking

查看:155
本文介绍了Singleton with Enum vs Singleton with double-checked locking的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在多线程环境中哪一个更好。我理解Singleton作为Enum类型在加载类时创建一个实例。除此之外我没有看到任何其他重要的东西。有什么优点和缺点吗?

I am wondering which one is better in practice in a multithreaded environment. I understand Singleton as Enum type creates an instance when the class is loaded. Other than that I don't see anything else significant. Is there any pros and cons ?

单身作为枚举类型:

Singleton as Enum type:

 public enum Singleton {
      INSTANCE;
      public void doSomething(){ ... }
 }

单身人士双重检查锁定

Singleton with double-checked locking:

 public class Singleton{
      private volatile static Singleton instance;

      private Singleton(){}
      public static Singleton getInstance(){
           if(instance == null){
                 synchronized(Singleton.class){
                       if(instance == null){
                           instance = new Singleton();
                       }
                 }
           }
           return instance;
      }

 }


推荐答案

通常在多线程应用程序中,更简单,更容易理解的代码更有可能工作。

Often in multi-threaded applications, simpler, easier to understand code is more likley to work.

在我看来,第一个例子是显着比第二个更简单,这才是最重要的。

To my mind the first example is significantly simpler than the second and that is what matters.

使用 enum 的主要专业人士是更简单,更复杂的例子是不合理的。双锁定示例允许您以有趣的方式更改单例以进行单元测试,但我相信这可以通过另一种方式解决这个问题。

The main pro of using an enum is its much simpler and the more complicated example is not justified. The double locking example allows you to change the singleton in interesting way for unit tests, but I believe what this gives you can be solved another way.

这篇关于Singleton with Enum vs Singleton with double-checked locking的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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