Categories
design-patterns java singleton

What is an efficient way to implement a singleton pattern in Java? [closed]

845

What is an efficient way to implement a singleton design pattern in Java?

3

  • 2

    “What is an efficient way to implement a singleton pattern in Java?” please define efficient.

    Apr 6, 2016 at 13:13

  • 1

    medium.com/@kevalpatel2106/… . This is the complete article on how to achieve thread, reflection and serialization safety in the singleton pattern. This is the good source to understand the benefits and limitations of singleton class.

    Nov 30, 2016 at 9:20

  • As Joshua Bloch points out in Effective Java, enum singleton is the best way to go. Here I have categorized the various implementations as lazy/eager etc.

    – isaolmez

    Apr 13, 2017 at 13:21


803

Use an enum:

public enum Foo {
    INSTANCE;
}

Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

public enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}

Edit: An online portion of “Effective Java” says:

“This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.”

28

  • 214

    I think people should start looking at enums as just a class with a feature. if you can list the instances of your class at compile time, use an enum.

    – Amir Arad

    Oct 7, 2008 at 7:17

  • 7

    I personally don’t often find the need to use the singleton pattern directly. I sometimes use spring’s dependency injection with an application context that contains what it refers to as singletons. My utility classes tend to only contain static methods, and I don’t need any instances of them.

    Jul 16, 2009 at 4:01

  • 3

    Hi, Can anybody tell me how this type of singleton can be mocked and tested in test cases. I tried to swap fake singleton instance for this type but couldn’t.

    Mar 18, 2011 at 11:03

  • 31

    I guess it makes sense, but I still don’t like it. How would you create a singleton that extends another class? If you use an enum, you can’t.

    – chharvey

    Sep 5, 2011 at 21:28

  • 11

    @bvdb: If you want lots of flexibility, you’ve already screwed up by implementing a singleton in the first place. The ability to create an independent instance when you need it is rather priceless in itself.

    – cHao

    Sep 22, 2013 at 16:43


237

Depending on the usage, there are several “correct” answers.

Since Java 5, the best way to do it is to use an enum:

public enum Foo {
   INSTANCE;
}

Pre Java 5, the most simple case is:

public final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }

    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot clone instance of this class");
    }
}

Let’s go over the code. First, you want the class to be final. In this case, I’ve used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.

When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

You can use a private static class to load the instance. The code would then look like:

public final class Foo {

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }
}

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

When you also want to be able to serialize your object you need to make sure that deserialization won’t create a copy.

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.

15

  • 33

    The check for reflection is useless. If other code is using reflection on privates, it’s Game Over. There’s no reason to even try to function correctly under such misuse. And if you try, it will be an incomplete “protection” anyways, just a lot of wasted code.

    Feb 24, 2009 at 21:42

  • 5

    > “First, you want the class to be final”. Could someone elaborate on this please?

    – Debajit

    Mar 2, 2009 at 21:09

  • 2

    The deserialisation protection is completely broken (I think this is mentioned in Effective Java 2nd Ed).

    Jul 15, 2009 at 22:45

  • 9

    -1 this is absolutely not the most simple case, it’s contrived and needlessly complex. Look at Jonathan’s answer for the actually most simple solution that is sufficient in 99.9% of all cases.

    Sep 30, 2009 at 8:16

  • 2

    This is useful when your singleton needs to inherit from a superclass. You cannot use the enum singleton pattern in this case, since enums cannot have a superclass (they can implement interfaces, though). For example, Google Guava uses a static final field when the enum singleton pattern is not an option: code.google.com/p/guava-libraries/source/browse/trunk/guava/src/…

    Jun 23, 2011 at 12:15


146

Disclaimer: I have just summarized all of the awesome answers and wrote it in my own words.


While implementing Singleton we have two options:

  1. Lazy loading
  2. Early loading

Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.

The most simple way of implementing a singleton is:

public class Foo {

    // It will be our sole hero
    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            // SHOUT
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }
}

Everything is good except it’s an early loaded singleton. Lets try lazy loaded singleton

class Foo {

    // Our now_null_but_going_to_be sole hero
    private static Foo INSTANCE = null;

    private Foo() {
        if (INSTANCE != null) {
            // SHOUT
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        // Creating only  when required.
        if (INSTANCE == null) {
            INSTANCE = new Foo();
        }
        return INSTANCE;
    }
}

So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.
So let’s protect it from evil multi threading:

class Foo {

    private static Foo INSTANCE = null;

    // TODO Add private shouting constructor

    public static Foo getInstance() {
        // No more tension of threads
        synchronized (Foo.class) {
            if (INSTANCE == null) {
                INSTANCE = new Foo();
            }
        }
        return INSTANCE;
    }
}

But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:

class Foo {

    // Pay attention to volatile
    private static volatile Foo INSTANCE = null;

    // TODO Add private shouting constructor

    public static Foo getInstance() {
        if (INSTANCE == null) { // Check 1
            synchronized (Foo.class) {
                if (INSTANCE == null) { // Check 2
                    INSTANCE = new Foo();
                }
            }
        }
        return INSTANCE;
    }
}

This is called the “double-checked locking idiom”. It’s easy to forget the volatile statement and difficult to understand why it is necessary.
For details: The “Double-Checked Locking is Broken” Declaration

Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:

class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static volatile Foo INSTANCE = null;

    // The rest of the things are same as above

    // No more fear of serialization
    @SuppressWarnings("unused")
    private Object readResolve() {
        return INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.

Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    // Wrapped in a inner static class so that loaded only when required
    private static class FooLoader {

        // And no more fear of threads
        private static final Foo INSTANCE = new Foo();
    }

    // TODO add private shouting construcor

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    // Damn you serialization
    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

Yes, this is our very same hero 🙂

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.

And we have come so far. Here is the best way to achieve everything we did is best possible way:

public enum Foo {
    INSTANCE;
}

Which internally will be treated like

public class Foo {

    // It will be our sole hero
    private static final Foo INSTANCE = new Foo();
}

That’s it! No more fear of serialization, threads and ugly code. Also ENUMS singleton are lazily initialized.

This approach is functionally equivalent to the public field approach,
except that it is more concise, provides the serialization machinery
for free, and provides an ironclad guarantee against multiple
instantiation, even in the face of sophisticated serialization or
reflection attacks. While this approach has yet to be widely adopted,
a single-element enum type is the best way to implement a singleton.

-Joshua Bloch in “Effective Java”

Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience 🙂

Updated it on my blog.

11

  • 3

    Just a clarification: singletons implemented using enum are initialized lazily. Details here: stackoverflow.com/questions/16771373/…

    – user246645

    Aug 23, 2013 at 7:10

  • 2

    great answer. one last thing, override clone method to throw exception.

    Nov 20, 2014 at 8:01

  • 2

    @xyz nice explanations, I really enjoyed and learned very easily and I hope never forgot this

    – Premraj

    Jun 30, 2015 at 4:26

  • 1

    One of the best answers I have ever red on stackoverflow. Thanks!

    Nov 14, 2017 at 14:27

  • 1

    There is a serialization problem with using enums as a singleton: Any member field values are not serialized and therefore not restored. See Java Object Serialization Specification, version 6.0. Another problem: No versioning — all enum types have a fixed serialVersionUID of 0L. Third problem: No customization: Any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization.

    Jul 24, 2019 at 4:22