design-patterns-java icon indicating copy to clipboard operation
design-patterns-java copied to clipboard

Overcomplicated singleton

Open Miha-x64 opened this issue 6 years ago • 4 comments

https://github.com/RefactoringGuru/design-patterns-java/blob/760142524cef5697bb0296f6400340380a962357/src/refactoring_guru/singleton/example/thread_safe/Singleton.java#L43-L52

Why do you prefer this overcomplicated code instead of concise, simple, thread-safe, and lazy enough

private static final Singleton instance = new Singleton();

?

Miha-x64 avatar May 21 '19 07:05 Miha-x64

private static final Singleton instance = new Singleton(); is actually the eager initialization which will cause a slowdown in your application during startup.

The alternatives that can be used in place of the above mentioned double-check synchronized lock is Bill-Pugh's Singleton & Enums, both of these are thread-safe and allows lazy initialization.

bhaskar253 avatar Jul 18 '20 17:07 bhaskar253

will cause a slowdown

This is wrong because classes are loaded lazily, according to JVM spec. Enums are genereted in exactly same way: public static constants are assigned during static initialization.

Miha-x64 avatar Jul 18 '20 19:07 Miha-x64

@Miha-x64 what spec do you reference exactly?

roeniss avatar Apr 27 '21 16:04 roeniss

@roeniss https://docs.oracle.com/javase/specs/jls/se16/html/jls-12.html#jls-12.4.1

Miha-x64 avatar Apr 27 '21 19:04 Miha-x64