Thread Safe Singletons in Java

前端 未结 1 1131
感动是毒
感动是毒 2020-12-07 21:18

The wikipedia article on Singletons mentions a few thread safe ways to implement the structure in Java. For my questions, let\'s consider Singletons that have lengthy initi

相关标签:
1条回答
  • 2020-12-07 21:50

    Answer 1: static synchronized methods use the class object as the lock - ie in this case Singleton.class.

    Answer 2: The java language, among other things:

    • loads classes when they are first accessed/used
    • guarantees that before access to a class is allowed, all static initializers have completed

    These two facts mean that the inner static class SingletonHolder is not loaded until the getInstance() method is called. At that moment, and before the thread making the call is given access to it, the static instance of that class is instantiated as part of class loading.

    This all means we have safe lazy loading, and without any need for synchronization/locks!

    This pattern is the pattern to use for singletons. It beats other patterns because MyClass.getInstance() is the defacto industry standard for singletons - everyone who uses it automatically knows that they are dealing with a singleton (with code, it's always good to be obvious), so this pattern has the right API and the right implementation under the hood.

    btw Bill Pugh's article is worth reading for completeness when understanding singleton patterns.

    0 讨论(0)
提交回复
热议问题