Sunday, October 27, 2013

What is an efficient way to implement a singleton pattern in Java?
share|improve this question
1 
Nicolas's class is not thread-safe. If two threads, Thread 1 and Thread 2, call getInstance() at the same time, two instances can be created if Thread 1 is pre-empted just after it enters the if block and control is subsequently given to Thread 2. –  dogbane Sep 16 '08 at 9:43
13 
singletons are considered to be anti-patterns since over 10 years ;) –  ivan_ivanovich_ivanoff Mar 25 '09 at 23:47
31 
@ivan_ivanovich_ivanoff and??? This comment is absolutely out of place. It's a valid design pattern. – Gabriel Llamas Jun 24 '11 at 20:41 
6 
So something can be considered as a design pattern and an anti-pattern at the same time. Context really is everything. Interesting thought... –  Alexis Dufrenoy Jan 23 '12 at 13:13 
1 
I've written this post where I tried to summarize all Singleton implementations in Java I've encountered in my practice. I hope it will be useful. Using single-element enumeration is certainly the best way when it comes to Java 5 and later. –  Andrey Polunin Jan 11 at 22:16
show 1 more comments

21 Answers

up vote271down voteaccepted
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));
       }
   }
"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."
share|improve this answer
67 
I just don't like it. it seems just so hacky. –  Stu Thompson Sep 16 '08 at 14:55
26 
I think it's the most elegant solution there can be with Java 1.5 –  GHad Sep 22 '08 at 20:46
83 
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 '08 at 7:17
12 
I'm with Amir. The name "enum" has so many preconceived expectations, that it's takes a little while to sink in that, in Java, enumerations are really much more than a list of symbolic constants. –  Dave Ray Dec 2 '08 at 21:16
5 
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. –  Stephen Denne Jul 16 '09 at 4:01
show 15 more comments
Depending on the usage, there are several "correct" answers.
Since java5 the best way to do it is to use an enum:
public enum Foo {
   INSTANCE;
}
Pre java5, 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;
    }
}
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 apublic 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.
share|improve this answer
8 
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. –  Wouter Coekaerts Feb 24 '09 at 21:42
2 
> "First, you want the class to be final". Could someone elaborate on this please? –  Nocturne Mar 2 '09 at 21:09
 
The deserialisation protection is completely broken (I think this is mentioned in Effective Java 2nd Ed). – Tom Hawtin - tackline Jul 15 '09 at 22:45
4 
-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. –  Michael BorgwardtSep 30 '09 at 8:16
 
No, it is not. As the language changes and time passes, progressive insight learned me that for java5 and later, the best way to do it is to use the enum solution, as suggested by spdenne –  Roel Spilker Oct 8 '09 at 11:24
show 2 more comments
The solution posted by Stu Thompson is valid in Java5.0 and later. But I would prefer not to use it because I think it is error prone.
It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe anymore due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of Java Concurrency in Practice. In short: This pattern (prior to Java5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.
This pattern was invented for performance optimization. But this is really not a real concern anymore. The following lazy initialization code is fast and -more importantly- easier to read.
class Bar {
    private static class BarHolder {
        public static Bar bar = new Bar();
    }

    public static Bar getBar() {
        return BarHolder.bar;
    }
}
share|improve this answer
1 
Fair enough! I'm just comfortable with volatile and it's use. Oh, and three cheers for JCiP. –  Stu ThompsonSep 16 '08 at 14:40
 
Oh, this is apparently the approach advocated by William Pugh, of FindBugz fame. –  Stu Thompson Sep 16 '08 at 14:42
4 
@Stu The first edition of Effective Java (copyright 2001) details this pattern under item 48. –  Pascal ThiventMar 6 '10 at 1:31
 
@Bno: What about making constructor private? –  Karna Mar 18 at 18:16
Thread safe in Java 5+:
class Foo {
    private static volatile Bar bar = null;
    public static Bar getBar() {
        if (bar == null) {
            synchronized(Foo.class) {
                if (bar == null)
                    bar = new Bar(); 
            }
        }
        return bar;
    }
}

EDIT: Pay attention to the volatile modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization does not take care of that--it only serializes access to that block of code.
EDIT 2: @Bno 's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.
share|improve this answer
 
Where can I learn more about the volatile modifier? –  eleven81 Jan 16 '09 at 17:16
 
2 
I think it is important to mention about reflection attacks. True that most developers don't need to worry about, but it seems that examples like these (over Enum-based singletons) should include either code that protects against multiple-instantiation attacks or simply put a disclaimer indicating such possibilities. – luis.espinal Oct 27 '10 at 14:16
Forget lazy initialization, it's too problematic. This is the simplest solution:
public class A {    

    private static A singleton = new A();

    private A() {}

    public static A getInstance() {
        return singleton;
    }
}
share|improve this answer
10 
singleton instance variable can be made final also. e.g., private static final A singleton = new A(); –  jatanpSep 16 '08 at 11:54
8 
That effectively is lazy initialisation, since the static singleton won't be instantiated until the class is loaded and the class won't be loaded until it's needed (which will be right about the time that you first reference the getInstance() method). –  Dan Dyer Sep 16 '08 at 12:48
1 
If class A does get loaded way before you want the static to be instantiated, you can wrap the static in a static inner class to decouple the class initialisation. –  Tom Hawtin - tackline Sep 16 '08 at 12:54
 
I agree with @Dan Dayer, this is example it is lazy initialization. If there were other methods on the class, then it might be...depends on which static method gets called first. (Imagine a public static void doSomething() in class A being called first--A is instanced, but not used.) –  Stu Thompson Sep 16 '08 at 14:26
 
why would you have another static method in this class and not want to use its getInstance(). One class One Responsibility out the door? –  tgkprog Jun 10 at 14:03
show 1 more comments
Make sure that you really need it. Do a google for "singleton anti-pattern" to see some arguments against it. There's nothing inheritantly wrong with it I suppose but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular I've found dependency injection more useful particularly if you are also using unit tests because DI allows you to use mocked resources for testing purposes.
share|improve this answer
 
you can inject mock values with the traditional method too but i guess its not the standard / srping way so its extra work with only gain being legacy code ... –  tgkprog Jun 10 at 14:05
Don't forget the Singleton is only a Singleton for the Classloader that loaded it. If you are using multiple loaders (Containers) each COULD have its own version of the Singleton.
share|improve this answer
2 
To avoid, using a utility class, register a container holding the singleton instance into the platform MBeanServer. The ObjectName is ~the singleton class name. If INSTANCE is null, the getInstance checks the MBeanServer. If MBean exists, instance is accessed through an attribute in the container. –  NicholasJan 5 '09 at 22:40
I'm mystified by some of the answers that suggest DI as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g. per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.
So my answer to the OP would be (in all but the most trivial sample code) to:
  1. Use a DI framework like Spring, then
  2. Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.
This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).
share|improve this answer
 
Downvoted because? –  Andrew Swan Nov 24 '09 at 0:00
1 
Perhaps because people disagree with you. I haven't downvoted you, but i do disagree: i think DI can be used to solve the same problems singletons are. This is based on understanding "singleton" to mean "an object with a single instance which is accessed directly by a global name", rather than just "an object with a single instance", which is perhaps slightly tricksy. –  Tom Anderson Aug 6 '12 at 17:00
1 
To expand on that slightly, consider a TicketNumberer which needs to have a single global instance, and where you want to write a class TicketIssuer which contains a line of code int ticketNumber = ticketNumberer.nextTicketNumber();. In traditional singleton thinking, the previous line of code would have to be something like TicketNumberer ticketNumberer = TicketNumberer.INSTANCE;. In DI thinking, the class would have a constructor like public TicketIssuer(TicketNumberer ticketNumberer) { this.ticketNumberer = ticketNumberer; }. –  Tom Anderson Aug 6 '12 at 17:07
1 
And it becomes somebody else's problem to call that constructor. A DI framework would do it with a global map of some sort; a handbuilt DI architecture would do it because the app's main method (or one of its minions) would create the dependency and then call the constructor. Essentially, the use of a global variable (or a global method) is just a simple form of the dreaded service locator pattern, and can be replaced with dependency injection, just like any other use of that pattern. –  Tom Anderson Aug 6 '12 at 17:09
Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.
Personally I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody, they're used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like Inversion of Control (IoC) or Dependency Injection (DI) for a nice middleground.
If you really need one then wikipedia has a good example of a proper implementation of a singleton.
share|improve this answer

No comments:

Post a Comment