The Java Singleton pattern belongs to the family of design patterns that governs the instantiation process. A Singleton is an object that cannot be instantiated.

This design pattern suggests that at any time there can only be one instance of a Singleton (object) created by the JVM. You implement the pattern by creating a class with a method that creates a new instance of the class if one does not exist. If an instance of the class exists, it simply returns a reference to that object.

How the Singleton pattern works

Here's a typical example of Singleton:

public class Singleton {
private final static Singleton INSTANCE = new Singleton();

// Private constructor suppresses generation of
// a (public) default constructor
private Singleton() {}


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

The classic Singleton does not use direct instantiation of a static variable with declaration -- it instantiates a static instance variable in the constructor without checking to see if it already exists:

public class ClassicSingleton {
private static ClassicSingleton INSTANCE = null;
private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new ClassicSingleton();
}
return INSTANCE;
}
}

The Singleton class's default constructor is made private, which prevents the direct instantiation of the object by other classes using the new keyword. A static modifier is applied to the instance method that returns the Singleton object; it makes this a class level method that can be accessed without creating an object.

When you need Singleton

Singletons are truly useful when you need only one instance of a class, and it is undesirable to have more than one instance of a class.

When designing a system, you usually want to control how an object is used and prevent users (including yourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It's not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.

The Singleton pattern is often used in conjunction with the factory method pattern to create a systemwide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Abstract Windowing Toolkit (AWT). In GUI applications, you often need only one instance of a graphical element per application instance, like the Print dialog box or the OK button.

Watch out for potential problems

Although the Singleton design pattern is one of the simplest design patterns, it presents a number of pitfalls.

Construct in multi-threaded applications
You must carefully construct the Singleton pattern in multi-threaded applications. If two threads are to execute the creation method at the same time when a Singleton does not exist, both must check for an instance of the Singleton, but only one thread should create the new object. The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated. This is a thread-safe version of a Singleton:

public class Singleton
{
// Private constructor suppresses generation
// of a (public) default constructor
private Singleton() {}

private static class SingletonHolder
{
private final static Singleton INSTANCE = new Singleton();
}


public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}

For an alternative solution, you can add the synchronized keyword to the getInstance() method declaration:

public static synchronized Singleton getInstance()

Think ahead about cloning prevention
You can still create a copy of the Singleton object by cloning it using the Object's clone() method. To forbid this, you need to override the Object's clone method, which throws a CloneNotSupportedException exception:

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

Consider making the singleton class final
You may want to make the Singleton class final to avoid sub classing of Singletons that may cause other problems.

Remember about garbage collection
Depending on your implementation, your Singleton class and all of its data might be garbage collected. This is why you must ensure that there must be a live reference to the Singleton class when the application is running.

Conclusion

The Singleton pattern is widely used and has proved its usability in designing software. Although the pattern is not specific to Java, it has become a classic in Java programming. Despite its simplicity, remember the limitations of the Singleton pattern that I describe in this article.

Interpreting Java This was published in Interpreting Java, check every Tuesday for more stories

Related links

Comments

1

Tahir Ak - 26/09/07

Really helpful especially the limitations described.

» Report offensive content

2

mohit rastogi - 05/10/07

this is the good note.
i have learnt a lot form this.

» Report offensive content

3

padmapriya - 15/09/08

its really helpful for me.
its is like small notes for singleton object.
thanks for sending the above coding and explanation

» Report offensive content

4

rolls - 14/05/09

i

class CMySingleton
{
public:
static CMySingleton& Instance()
{
static CMySingleton singleton;
return singleton;
}

// Other non-static member functions
private:
CMySingleton() {}; // Private constructor
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator=(const CMySingleton&); // Prevent assignment
};

http://usedauto.com.ua/cars/?cid=2

» Report offensive content

5

Nell - 18/08/09

Greeting. Let not the sands of time get in your lunch. Help me! There is an urgent need for sites: Benefit cosmetics available. I found only this - <a href="http://www.hockenheim-classics.de/Members/Benefit/benefit-cosmetics-gossip">benefit cosmetics gossip</a>. You are here shopping health and beauty cosmetics. Dkny jacquard harness tote medium and large sizes. THX :cool:, Nell from Islands.

Benefit cosmetics available

» Report offensive content

6

Nuru - 08/09/09

Hi everyone. Thanks for your site. Help me! Help to find sites on the: Axiom sales force, first, dependent to related news, information changes have licensed then direct.. I found only this - [URL=http://www.fh-krems.ac.at/Members/Sales]dedicated Sales force for multiple markets[/URL]. Small problems of an sfa phase can sell companies marketing, allergy amount and disease insurance. Astelles protopic sales force: the advertisers market should be large to concentrate sales makeup, without creativity of the fasteners, and be digital to leave of the software individual or the classification of buyer of the advantage and other affiliate competitors. Thanks for the help :-), Nuru from Sierra.

Sales force models

» Report offensive content

7

Lakshminath - 04/12/09

Good explanation , short and precise but very sensible... thank you very much.

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

7

Lakshminath - 12/04/09

Good explanation , short and precise but very sensible... thank you very much. ... more

6

Nuru - 09/08/09

Hi everyone. Thanks for your site. Help me! Help to find sites on the: Axiom sales force, first, dependent to related ... more

5

Nell - 18/08/09

Greeting. Let not the sands of time get in your lunch. Help me! There is an urgent need for sites: Benefit ... more

Log in


Sign up | Forgot your password?

  • Staff Microsoft shows off IE9 preview

    This week, highlights from Microsoft's MIX10 conference and more in the Roundup. Read more »

    -- posted by Staff

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!