Why enum singleton is lazy?

后端 未结 2 841
后悔当初
后悔当初 2021-01-23 13:39

I saw answers like these, tried to clarify via comments, and was unsatisfied by examples here.

Maybe it\'s time for this specific question...

Why enum singleton im

2条回答
  •  不要未来只要你来
    2021-01-23 14:21

    The first two linked answers (by Peter Lawrey and Joachim Sauer) both agree that enums are not lazily initialized. Answers in the third link are simply wrong about what lazy initialization means.

    The recommendation to use enums as singletons originates from Josh Bloch's Effective Java. Notably, the chapter on enum singletons makes no mention of laziness. There is a later chapter dedicated to lazy initialization, that likewise makes no mention of enums. The chapter contains two highlights.

    • If you need to use lazy initialization for performance on a static field, use the lazy initialization holder class idiom.
    • If you need to use lazy initialization for performance on an instance field, use the double-check idiom.

    Undoubtedly, enums would be another idiom on this list if they were in any way lazily initialized. In fact they are not, although confusion about the meaning of lazy initialization results in some incorrect answers, as the OP shows.

提交回复
热议问题