Singleton with Enum vs Singleton with double-checked locking

后端 未结 3 1843
暖寄归人
暖寄归人 2021-01-13 12:13

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 t

3条回答
  •  -上瘾入骨i
    2021-01-13 12:58

    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.

    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.

提交回复
热议问题