Skip to content

Overcomplicated singleton #10

Open

Description

@Miha-x64

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();

?

Activity

  1. bhaskar253 commented on Jul 18, 2020

    @bhaskar253

    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.

  2. Miha-x64 commented on Jul 18, 2020

    @Miha-x64
    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.

  3. roeniss commented on Apr 27, 2021

    @roeniss

    @Miha-x64 what spec do you reference exactly?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions