Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overcomplicated singleton #10

Open
Miha-x64 opened this issue May 21, 2019 · 4 comments
Open

Overcomplicated singleton #10

Miha-x64 opened this issue May 21, 2019 · 4 comments

Comments

@Miha-x64
Copy link

Singleton result = instance;
if (result == null) {
synchronized (Singleton.class) {
result = instance;
if (result == null) {
instance = result = new Singleton(value);
}
}
}
return instance;

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

private static final Singleton instance = new Singleton();

?

@bhaskar253
Copy link

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.

@Miha-x64
Copy link
Author

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.

@roeniss
Copy link

roeniss commented Apr 27, 2021

@Miha-x64 what spec do you reference exactly?

@Miha-x64
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants