I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Design Patterns Uncovered: The Singleton Pattern

02.15.2010
| 31227 views |
  • submit to reddit

The next pattern in our series is the Singleton pattern. Singleton is probably the most infamous pattern, as it's use causes a divide in the development community- some say it belongs, others say it's against object-orientation.

Singletons in the Real World 

In the real world singletons represent anything that is unique, so in theory, every person is a singleton. Putting things into a more concrete example, your house probably has just one central electical fuse box. 

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Singleton Pattern

Singleton is known as a creational pattern - it's used to construct objects such that they can be decoupled from the implementing system. The definition of Singleton provided in the original Gang of Four book on Design Patterns states: 

Ensure a class has only one instance and provide a global point of access to it.

Across all 23 design patterns, the diagram definition of the Singleton pattern is the simplest:

 

We just provide one point of access to create an instance of the Singleton class. The constructor is kept private, giving the getInstance() method the responsibility of providing access to the Singleton.

 

 This sequence diagram shows how simple it is for a client to get an instance of the Singleton.

Where Would I Use This Pattern?

When you need to ensure there's one instance of an object, available to a number of other classes, you may want to use the Singleton pattern. Singletons are used a lot where you need to provide a registry, or something like a thread pool. Logging is also another popular use of Singletons, providing one single access point to an applications log file.

So How Does It Work In Java?

This example will show how to put together the classic Singleton in Java, without thinking about the threading complications which we discuss later on in this article. 

The Singleton class has some characteristics that we generally want to ensure two things: 

  • We lazily load our singleton based on the first request for access to it.
  • There is no other way of instantiating our Singleton  

Keeping this in mind, here is our Java representation of a Singleton.

public class Singleton
{
private Singleton instance;

private Singleton()
{
}

public static Singleton getInstance()
{
if(instance==null)
{
instance = new Singleton();
}
return instance;
}


}

We maintain the lazy loading principle here by only creating the instance when it is null, which will always be on the first call. Additionally, because we use a private constructor, we can only create the Singleton by calling the getInstance() method. 

For completeness, here is how a client can access the Singleton:

//access the singleton
Singleton singleton = Singleton.getInstance();
//use the singleton

As you can see, it's fairly simple - but there are downsides.

Watch Out for the Downsides

As I mentioned at the beginning of this article, the Singleton is infamous in object oriented systems. A lot of the time the Singleton is used as a shortcut, so that the designer doesn't need to think properly about object visibility. If you're hacking in a Singleton so that there is global access to a resource, maybe it's not the right thing to do. It might be better to work out how to pass the reference to that resource around properly.

Another important consideration is multi-threading. If two threads call the getInstance() method at the same time, you can end up with two singletons. Making the getInstance() method synchronised solves this issue, but then you have the performance cost - calling a synchronised version of getInstance() will be slower than the non-synchronized version.  However, maybe the best way around this is to sacrifice lazy-loading in the Singleton, ensuring there can only ever be on instance. A number of alternatives are listed here

Google have even provided a Singleton Detector, to discourage their use in programs. The page "Why Singletons are Controversial" gives another good overview on the pitfalls around the pattern.

First, programs using global state are very difficult to test. ...the singleton user and the singleton become inextricably coupled together. It is no longer possible to test the user without also testing the singleton.
.....

Second, programs that rely on global state hide their dependencies.

If you've been following this series you'll notice that no other pattern has had so many downsides and cautionary notes. It's true for all patterns that you need to carefully consider it's applicability to your problem before using it. With Singleton, consider it twice as much.

Other Articles in This Series
The Observer Pattern
The Adapter Pattern
The Facade Pattern
The Factory Method Pattern
The Abstract Factory Pattern
The Singleton Pattern
The Strategy Pattern
The Visitor Pattern

Next Up

Later this week, we'll be taking a look at another creational pattern -  the Factory pattern.

Tags:

Comments

Kris Schneider replied on Mon, 2010/02/15 - 11:57am

You should really encourage the use of proper lazy-loading: Initialize-on-demand.

Pooria Mellati replied on Mon, 2010/02/15 - 5:56pm

 Hey, nice post!

Using singletons gets a bit crazy at times for me though!

For example, in your provided example code, the singleton class returns an instance of itself, i.e. the user of the class would be using a concrete class to get an instance of it. However, we are supposed to prefer programming to interfaces (and not to concrete implementations), so it seems like we would be more interested in "Ensuring an Interface has only one instance and providing a global point of access to it.".

With that kind of thinking I usually end up taking an interface and making it a singleton, so that it returns a single instance of one of its subtypes.

E.g. I usually make my abstract factories to be singletons, so that only a certain type of a concrete factory will be used in my programs!

What do you think? Is this a normal way of using singletons? Does anyone think I am missing something?

Dhaval Nagar replied on Tue, 2010/02/16 - 1:25am

Nice explanation.

But people using Dependency Injection mechanism really avoid using the Singleton pattern. Well though its not the fault of the pattern itself but the way it's being used. Though i would recommend learning original patterns to find out where one should use it and where not to.

Here Google suggests Dependency Injection to avoid Singletons. http://googletesting.blogspot.com/2008/05/tott-using-dependancy-injection-to.html

James Sugrue replied on Tue, 2010/02/16 - 2:00am in response to: Pooria Mellati

I think it's probably common enough that an AbstractFactory would be a singleton. Singleton probably pops up as a solution in the implementation of a few creational patterns.

haroon idress replied on Tue, 2010/02/16 - 3:15am

I Implement Singleton  this way.Its a thread safe and no performance hit.Is any draw back of implementing Singleton this way.

01.    public class Singleton
02. {
03. private static Singleton instance=new Singleton();
04.
05. private Singleton()
06. {
07. }
08.
09. public static Singleton getInstance()
10. {
11. return instance;
12. }
13.
14.
15.}

James Sugrue replied on Tue, 2010/02/16 - 5:21am in response to: haroon idress

I don't think there's any drawbacks to that approach. It's the same "initialization on demand" approach that Kris suggested above.

Magnus Smith replied on Tue, 2010/02/16 - 8:50am in response to: James Sugrue

No it isn't

The Singleton object is created at line 3 when the class is first loaded and not when getInstance() is called. 

It avoids the thread safety issue but has the penalty of initialisation during initial class loading.

The initialisation on demand holder that Krys mentioned addresses both issues of thread saftey and initialisation on demand.

Nathan Dolan replied on Tue, 2010/02/16 - 9:24am

When using that approach you're as well to just expose the instance as a public static final field e.g.

public class Singleton {

public static final Singleton instance = new Singleton(...);

private Singleton(...) {...}

...

}

 

There really is no reason to have a getter method in the same way you wouldn't have a getter for a string constant; i.e. a singleton is just an object constant.  Obviously declaring the instance as final is critical to this.

Note the only drawback of these approaches is that the instance and its constructor parameters are instantiated at class-load time rather than lazy-loaded on first use.  Normally this wouldn't be an issue but it may be in some contexts, in which case go with the (marginally) slower and (marginally) more cumbersome synchronized lazy-load getter approach.

It could be argued that singleton isn't really a "proper" pattern.  It is just a lazy-loaded (or not) constant that is defined in its own class.  People who don't like singletons actually don't like static members (even if they don't know it), normally because of testability concerns, which is fair enough.  Although I think the alternative can on occasion be less desirable.

Nathan Dolan replied on Tue, 2010/02/16 - 9:33am

Thanks Kris and Magnus for the Initialization on Demand link.  Not seen that before, looks a nice way of avoiding issues at class-load time if they crop up for static members that have state.

Mladen Girazovski replied on Tue, 2010/02/16 - 3:35pm

One of the problems with the Singleton Pattern is, that the way it is demonstrated here it mixes different concerns, namely how(often) an object is created and how it is accessed.

The instance field/getInstance methode ties the caller  to the static field/Method, hard to test or replace in general, best is to just avoid it, ever DI framework can offer the interesting bit of functionalit (only one instance) without all the other drawbacks of the GoF Singleton Pattern.

Of course, one singleton in an application won't hurt much, but if you're using more than one rethink your so called design.

There is a reason people have coined it an "Anti-Pattern".

 

Here is a good article from Fowler on DependencyInjection and ResourceLookup , the latter includes a singleton: http://www.martinfowler.com/articles/injection.html

Raging Infernoz replied on Tue, 2010/02/16 - 4:47pm

What about the inadvertant singletons found in static fields for mutable objects (e.g. TextFormats, Calendars etc), these can play havoc with unexpectedly multi-threaded code, my work collegue got bitten by this.

I've spent a lot of time, at work, writing ThreadLocal factory/facade classes to make these 'singletons' thread-safe, and try to educate my collegue that synchronized is not always the best or safest approach.

I see lazy loading mentioned here, but the need for a synchonized clause can make it expensive and it may be better done as a ThreadLocal, also never do a null check outside a synchronized block, because that anti-pattern can allow another thread to see a partially initialised object and cause bizarre errors.

nathandolan79,

The reason a singeton access method is provided is to hide how the object is constructed thus provide more flexibility for how the object is constructed e.g. there maybe dependencies for some singletons which prevent immediate construction.

migra,

You are inevitably going to need a singleton somewhere, otherwise you have to pass more objects (including factories) to methods, and hope you don't modify or duplicate these state!

No Singleton is not an anti-pattern, you just have to be carefull how and where you use it.

 

I regard a lot of code injection as a nasty smell (e.g. I detest Spring), because it can be even more dangerous, hard to understand, and track down than a misused singleton.

 

haroon idress replied on Wed, 2010/02/17 - 12:49am

Thanks Kris , Magnus and James Sugrue .Yes initializing on demand is much better appraoch for implementing singleton pattern

Mladen Girazovski replied on Wed, 2010/02/17 - 3:50am

migra,

You are inevitably going to need a singleton somewhere, otherwise you have to pass more objects (including factories) to methods, and hope you don't modify or duplicate these state!

No Singleton is not an anti-pattern, you just have to be carefull how and where you use it.

There is a huge difference between "need a singleton" and "need an singleton with static access", a framework like spring is providing me singletons without the need for the static access.

"Passing more objects" is just a different way of saying "Dependency Injection",a singleton with a static access is nothing else but a static ResourceLookup.

In my production code i have written not a single class with a static "getInstance()" Method or a public static field "instance".

 

The "initializing on demand" , also known as "lazy initialisation" with singletons is something that makes me laugh evertime i see it :)

People try to trade thread safety for performance, while it is not sure that it really saves performance, it is definiately sure that they are risking thread safety, and end up with more code. If a abstractfactory (like an AbstractDaoFactory if People are still using this pattern) is sure to be needed in an app, why not initialize it at startup and avoid all the threading issues?

Kris Schneider replied on Wed, 2010/02/17 - 9:34am in response to: Mladen Girazovski

@mgira: If you're implying that the initialize-on-demand idiom I linked to is not thread-safe, I'd love to see the explanation...

Mladen Girazovski replied on Wed, 2010/02/17 - 10:01am in response to: Kris Schneider

Sure, yours is thread safe, but not the one in showed in the article.

But it sufers the same general Problems that the GoF Singleton has, static access, mixed SoC, cumbersome to replace for testing, the anti OO approach of a global variable, and of course the fact that can can turn into an "Multiton" if a different class loader loads it.

Christopher Cobb replied on Sun, 2010/03/14 - 7:48am

The problem with classic singleton implementation in Java lies with the Java Memory Model.  It is all explained here:

Double-checked locking and the Singleton pattern: A comprehensive look at this broken programming idiom

The suggested alternative is to "use the Initialize-on-demand Holder Class idiom, which provides lazy initialization, is thread-safe, and is faster and less confusing:"

private static class LazySomethingHolder {
public static Something something = new Something();
}

...

public static Something getInstance() {
return LazySomethingHolder.something;
}

 

Muhammad Khojaye replied on Sun, 2010/10/17 - 3:11am in response to: Christopher Cobb

Deserialization of singleton can result in more than one instance. Althought readResolve method can work here.

Cloning could also result in breaking the singleton. Override cloning and throw exception could solve this.

nilesh gule replied on Tue, 2012/06/26 - 9:08am

I recently posted about implementing Singleton using C#. Since Java and C# and smilar in Syntax it might behelpful for someone interested or knowing both the languages.

http://www.nileshgule.com/2012/03/singleton-design-pattern.html

 

Peter Lawrey replied on Sun, 2013/07/14 - 3:48pm

You might like to add that since classes are lazily loaded and class initilization is thread safe, all you really need to do is have an enum.

Since Java 5.0 (released in 2004)

enum Singleton
    INSTANCE;
}

Since stateful singletons are very hard to test, I try to only use stateless singletons.

By comparison, using double checked locking adds complexity for little advantage.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.