java singleton instantiation

前端 未结 4 1002
暖寄归人
暖寄归人 2020-12-24 04:01

I\'ve found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I\'m using them in a multi-threaded environment and pr

4条回答
  •  心在旅途
    2020-12-24 04:31

    First of all, make absolutely sure that you need a singleton, and that you want to provide "global-level" access to the singleton. I've found that in many cases clients of the singleton have no need to know that it is a singleton. Rather, they just need to get a service when they are instantiated.

    Thus, regardless of how you obtain the singleton (if at all), consider changing the way your classes gain access to this object. While this means modifying constructors and changing "distribution changes", I've found that dependency injection frameworks reduce the cost. The DI framework can also then take care of singleton instantiation (e.g., Guice does that).

    Aside from that. option 3 is the typical and most common (and thread safe) version that I'm familiar with. Option 1 is mostly for non-lazy initialization (not always acceptable). I've never seen 2 used.

提交回复
热议问题