Java Singleton Pattern Tutorial

Singleton Pattern

The Singleton Pattern is one of the commonly used design templates when there needs to be a control on how an object can be created. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. The Singleton class抯 default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes).

One such scenario where it might prove useful is when we develop the Java Help Module in a project. JavaHelp is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications. Since at any time we can do only with one main Help object and use the same object in different screens, Singleton Pattern suits best for its implementation.

Implementing the Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor

publicclass SingletonObjectDemo

{

//Note that the constructor is private

private SingletonObjectDemo ()

{

// Optional Code

}

}

Step 2: Create a Method for getting the reference to the Singleton Object

publicclass SingletonObjectDemo{

privatestatic SingletonObject singletonObject;

//Note that the constructor is private

private SingletonObjectDemo (){

// Optional Code

}

publicstatic SingletonObjectDemo getSingletonObject(){

if (ref ==null){

singletonObject =new SingletonObjectDemo ();

}

return singletonObject;

}

}

We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

publicstaticsynchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one singleton object being created. This could violate singleton pattern principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning.

We can still be able to create a copy of the Object by cloning it using the Object抯 clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the Object抯 clone method which throws a CloneNotSupportedException exception.

public Object clone()throws CloneNotSupportedException{

thrownew CloneNotSupportedException();

}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class Singleton{

privatestatic Singleton singletonObject;

private Singleton(){

// Optional Code

}

publicstatic Singleton getSingletonObject()

{

if (singletonObject ==null){

singletonObject =new Singleton();

}

return singletonObject;

}

public Object clone()throws CloneNotSupportedException

{

thrownew CloneNotSupportedException();

}

}

publicclass SingletonObjectDemo{

publicstaticvoid main(String args[]){

//Singleton obj = new Singleton();Compilation error not allowed

//create the Singleton Object..

Singleton obj = Singleton.getSingletonObject();

// Your Business Logic

}

}

Regards,

Hemanth

[url=http://www.beginner-java-tutorial.com]Beginner Java Tutorial[/url]

[url=http://www.java-swing-tutorial.com]Java Swing Tutorial[/url]

[url=http://www.jdbc-tutorial.com]JDBC Tutorial[/url]Singleton Pattern

The Singleton Pattern is one of the commonly used design templates when there needs to be a control on how an object can be created. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. The Singleton class抯 default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes).

One such scenario where it might prove useful is when we develop the Java Help Module in a project. JavaHelp is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications. Since at any time we can do only with one main Help object and use the same object in different screens, Singleton Pattern suits best for its implementation.

Implementing the Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor

publicclass SingletonObjectDemo

{

//Note that the constructor is private

private SingletonObjectDemo ()

{

// Optional Code

}

}

Step 2: Create a Method for getting the reference to the Singleton Object

publicclass SingletonObjectDemo{

privatestatic SingletonObject singletonObject;

//Note that the constructor is private

private SingletonObjectDemo (){

// Optional Code

}

publicstatic SingletonObjectDemo getSingletonObject(){

if (ref ==null){

singletonObject =new SingletonObjectDemo ();

}

return singletonObject;

}

}

We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

publicstaticsynchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one singleton object being created. This could violate singleton pattern principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning.

We can still be able to create a copy of the Object by cloning it using the Object抯 clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the Object抯 clone method which throws a CloneNotSupportedException exception.

public Object clone()throws CloneNotSupportedException{

thrownew CloneNotSupportedException();

}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class Singleton{

privatestatic Singleton singletonObject;

private Singleton(){

// Optional Code

}

publicstatic Singleton getSingletonObject()

{

if (singletonObject ==null){

singletonObject =new Singleton();

}

return singletonObject;

}

public Object clone()throws CloneNotSupportedException

{

thrownew CloneNotSupportedException();

}

}

publicclass SingletonObjectDemo{

publicstaticvoid main(String args[]){

//Singleton obj = new Singleton();Compilation error not allowed

//create the Singleton Object..

Singleton obj = Singleton.getSingletonObject();

// Your Business Logic

}

}

Regards,

Hemanth

[url=http://www.beginner-java-tutorial.com]Beginner Java Tutorial[/url]

[url=http://www.java-swing-tutorial.com]Java Swing Tutorial[/url]

[url=http://www.jdbc-tutorial.com]JDBC Tutorial[/url]

[13078 byte] By [hemanthjavaa] at [2007-10-3 9:48:56]
# 1
not thread-safe. there are definate circumstances whereby two calling objects could get references to different "singleton" objects
georgemca at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
And don't forget to mention that singleton considered stupid: http://steve.yegge.googlepages.com/singleton-considered-stupidDenis Krukovsky http://blogoforum.com/blog/dkrukovsky
dkrukovskya at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 3

I have a doubt on Singleton pattern.

In a singleton class, if we don't implement the clone method, then we can't call the clone method from other classes, because it's protected.

If we write a main method in the same class and call clone method, it'll definitely throw CloneNotSupportedException, because it's not implementing the Cloneable interface.

Then why we need to override clone method? How does it violates the singleton pattern?

Please help me..

JavaForumkgvinotha at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 4

clone allows you to create a second instance of a class, whereas the point of the Singleton pattern is to allow only one instance. it's like locking your front door to keep people out, but leaving the front downstairs window wide open

the singletons described in this thread aren't particularly good. don't bother with them

georgemca at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 5

True, the clone method in Object is protected. Which means, you would not be able to invoke it from another client-class. Given this fact, one would be tempted not to implement a public clone() method in your class as suggested by the tutorial.

However there still exists a workaround by which someone can break your singleton pattern. Someone could create a subclass of your class like this:

* The subclass would implement the Cloneable interface

* The subclass adds a public clone() method. This public clone() method invokes the super.clone(). (Now, this is legal since Object.clone() is protected and can be accessed from its subclasses.)

Thus a client programmer can - by using a subclass - create multiple instances of your subclass (and thus multiple instances of the superclass).

It is to prevent this exploit that we implement a public clone() method and throw a CloneNotSupportedException. In that case, the subclass will always get an exception if it attempts a super.clone(). A subclass will never be able to successfully get a clone of your class.

roshankulkarnia at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 6
Why are you replying to a year old thread about how to write broken singletons?
dubwaia at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 7
Why are you replying to a year old thread about how to write broken singletons? And....providing irrelevant technical advice? (One can always circumvent access control.)
jschella at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...
# 8

Not that I like singletons, especially ones with global 'getInstance()' methods - if there's a n-1 relation, I far prefer passing in the singular object , which means you don't have waste time refactoring when you find the rules change.

> However there still exists a workaround by which someone can break your singleton pattern. Someone could create a subclass of your class like this:

> ...

Have you tried this? You can't subclass a class whose constructors are inaccessible:class Foo {

private Foo () { }

}

public class FooClone extends Foo {

}

$ javac -d build src/FooClone.java

src/FooClone.java:6: Foo() has private access in Foo

public class FooClone extends Foo {

So the only way you can invoke clone is via reflection:

import java.lang.reflect.*;

class Foo1 {

private Foo1 () { }

static final Foo1 INSTANCE = new Foo1();

}

class Foo2 implements Cloneable {

private Foo2 () { }

static final Foo2 INSTANCE = new Foo2();

public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}

}

public class FooClone {

public static void main (String...args) {

try {

Method cloneMethod = Object.class.getDeclaredMethod("clone");

cloneMethod.setAccessible(true);

try {

cloneMethod.invoke(Foo1.INSTANCE);

} catch (Exception ex) {

ex.printStackTrace(System.out);

}

try {

cloneMethod.invoke(Foo2.INSTANCE);

} catch (Exception ex) {

ex.printStackTrace(System.out);

}

} catch (Exception ex) {

ex.printStackTrace(System.out);

}

}

}

As Foo1 doesn't implement Cloneable, when you invoke its clone method it calls Object.clone, which checks for the marker interface, finds it's absent and throws CloneNotSupportedException.

As Foo2 overrides Object.clone(), when you invoke its clone method it calls the overridden method, which throws CloneNotSupportedException:

$ java -cp build FooClone

java.lang.reflect.InvocationTargetException

...

Caused by: java.lang.CloneNotSupportedException: Foo1

at java.lang.Object.clone(Native Method)

... 5 more

java.lang.reflect.InvocationTargetException

...

Caused by: java.lang.CloneNotSupportedException

at Foo2.clone(FooClone.java:12)

... 5 more

So the net effect of doing nothing about clone and doing what is recommended above about clone is the same, except that by overriding clone() you're telling people that you don't understand the default implementation's behaviour.

Pete

pm_kirkhama at 2007-7-15 5:05:54 > top of Java-index,Other Topics,Patterns & OO Design...