single-element enum type singletone with lazy loading capability

前端 未结 2 539
太阳男子
太阳男子 2021-01-02 09:03

I read many forums and posts about different style to implement single-tone pattern in java and seems \"Enum are the best way to implement singletone pattern in java\"!! I w

2条回答
  •  -上瘾入骨i
    2021-01-02 09:38

    The first time a class is used, it gets loaded by the JVM and all of its static initialization is done. the enum members are static , so they're all going to be initialized.

    Actually, classloader loads classes (sounds funny) only after you are accessing this classes first time. And only one reason to access enum-singleton class is to get it's instance.

    That is why single-element enum type singletone in Java are called lazy - it's value is not initialized before you first time access it.

    Similar questions:

    • Java: Lazy Initializing Singleton
    • Lazy-loaded singleton: Double-checked locking vs Initialization on demand holder idiom

提交回复
热议问题