Page 1 of 1

Singleton Class In Java Introduction to creating a Singleton class Rate Topic: ***** 1 Votes

#1 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Posted 11 January 2010 - 09:58 AM

*
POPULAR

Creating a Singleton Class in Java

A Singleton is an object that cannot be instantiated. There can be only one instance of a singleton created by the Java Virtual Machine (JVM).

Why is that useful, and why would you want to use such a thing…
Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance.

Now that you know what a singleton class is, and some of its uses, I'll move on to the main topic of that tutorial – the singleton class pattern.

The Singleton Class Pattern

Preventing direct instantiation
To prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

Here is a default class definition, for a Singleton Object class.
Of course, you may add some more initialization code as needed.
public class SingletonObject 
{
	/*The Constructor*/
	private SingletonObject()
	{
		/*No code required. may remain blank*/
	}
}


Ok, that seems fine. However, there is no way to use that class currently.
We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.
public class SingletonObject 
{
	/*The SingletonObject Object*/
	private static SingletonObject singletonRef;
	
	/*The Constructor*/
	private SingletonObject()
	{
		/*No code required. may remain blank*/
	}
	
	/*Method to get only one object of the SingletonObject*/
	public static SingletonObject getSingletonObject()
	{
		if(singletonRef == null)
		{
			singletonRef = new SingletonObject(); 
		}
		return singletonRef;
	}
}



We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration:
/*Method to get only one object of the SingletonObject*/
	public static synchronized SingletonObject getSingletonObject()
	{
		if(singletonRef == null)
		{
			singletonRef = new SingletonObject(); 
		}
		return singletonRef;
	}



Preventing the Singleton Object from being cloned.

Suppose one of the developers created a certain class, call it class A, and implemented the cloneable interface.
Public class A implements cloneable
{
	//code….
}


Then, he decided to extend the SingletonObject class with class A.
Public class SingletonObject extends A
{
	//code…
}


Now our SingletonObject also implements cloneable, and it is possible to clone objects, and thus ruining the idea of a Singleton object.

In order to prevent it, we must add our own clone method.
That way, if by chance someone extends the singleton object with a cloneable class, we will be able to handle it.

Here is the clone method to add to our class:
/*method to prevent cloning the SingletonObject*/
	public Object clone() throws CloneNotSupportedException
	{
								 /*preventing the singleton object from being cloned*/
		throw new CloneNotSupportedException();
	}



That is all for Singleton class. As you saw in that tutorial, creating a singleton class is quite easy.
Just block access to its constructor, prevent it from being cloned, and supply a method to get only one instance of that object.
Remember, This is only a general pattern. you may change it, and improve it to suit your needs :) .

Full code for a Singleton Class

public class SingletonObject 
{
	/*The SingletonObject Object*/
	private static SingletonObject singletonRef;
	
	/*The Constructor*/
	private SingletonObject()
	{
		/*No code required. may remain blank*/
	}
	
	/*Method to get only one object of the SingletonObject*/
	public static synchronized SingletonObject getSingletonObject()
	{
		if(singletonRef == null)
		{
			singletonRef = new SingletonObject(); 
		}
		return singletonRef;
	}
	
	/*method to prevent cloning the SingletonObject*/
	public Object clone() throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException();
	}
}



Is This A Good Question/Topic? 8
  • +

Replies To: Singleton Class In Java

#2 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Posted 20 February 2010 - 07:35 AM

Thanks
I never knew what an SingleTon is
thanks for the tutorial
Keep writing such tutorials
we are here to appreciate
Was This Post Helpful? 0
  • +
  • -

#3 Guest_sunil Yadav*


Reputation:

Posted 18 June 2010 - 03:30 AM

Thanks you very much to provide this very useful information about singleton class.
Very much appreciative.
Was This Post Helpful? 0

#4 Nasm  Icon User is offline

  • New D.I.C Head

Reputation: 27
  • View blog
  • Posts: 47
  • Joined: 10-June 10

Posted 19 June 2010 - 03:50 PM

You should use double locking instead. Since you only need to create a new instance the first time you lose performance having the getInstance method hold the lock even when there already is a instance. Otherwise it's a great guide. I personally never thought about that I had to override clone before.

class Singleton{
private volatile static Singleton instance;
private Singleton(){
//setup code here
}
public static Singleton  getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}


We save time by only locking the method the first time. Note that the second check as well as the volatile keyword is needed.
1) We use the first if check to be able to return fast in case a instance is already created. The second lock is needed however since our first wasn't synchronized and two thread is able to get by the lock at the same time in return creating two instances.
2) The volatile keyword is needed be course if we don't make the new operation atomic a second thread might return false on the first check even though the instance in the first thread is only half written.

Again I only wanted to point this out and not to criticise, it's a great guide otherwise.

This post has been edited by Nasm: 19 June 2010 - 03:52 PM

Was This Post Helpful? 0
  • +
  • -

#5 n8schatten  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 263
  • Joined: 07-December 10

Posted 21 March 2011 - 03:38 AM

Hi japanir,

just stumbled upon this post (better late than never ;) ). Basically I like the idea of singletons and I think you described it well.

Nonetheless, I think it's important to mention that this implementation only works well if you have exactly one ClassLoader. Otherwise you may encounter unexpected behavior, as there may be two or more different instances of your singleton in the system. (I learned this lesson about half a year ago,.. and I learned it the hard way :( )

One way to create a Singleton that will also work with more than one ClassLoader is to use an enum. You will lose the advantages of polymorphism at this point (since enums have a private constructor, thus are final) but you will have a real Singleton in every situation.

However, the Singleton as you described it above works really well most of the time for most people in most projects. Just make sure you know how many ClassLoaders are present in your system.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Posted 27 April 2011 - 08:02 PM

To follow on Nasm comments there is an easier way.
No need to have a synchronized getInstance() method if you are sure that your class will be instantiate. Like a database connection as example. So

private static SingletonObject singletonRef;

can become

private static SingletonObject singletonRef = new SingletonObject();

and then getInstance can simply become

public static SingletonObject getInstance() {
return singletonRef;
}

The synchronized mechanism you described can be usefull if the class requires a lot of memory and is not always used in the application.

Never though of the clone() method thow. Good show :^: japanir
Was This Post Helpful? 0
  • +
  • -

#7 nilotpal.barman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-May 11

Posted 05 May 2011 - 02:42 PM

Hi n8schatten,

Can you elaborate on how can a real singleton be created in a cluster environment or across many JVM's?
This will be really helpful.

Regards,
Nilotpal Barman

View Postn8schatten, on 21 March 2011 - 03:38 AM, said:

Hi japanir,

just stumbled upon this post (better late than never ;) ). Basically I like the idea of singletons and I think you described it well.

Nonetheless, I think it's important to mention that this implementation only works well if you have exactly one ClassLoader. Otherwise you may encounter unexpected behavior, as there may be two or more different instances of your singleton in the system. (I learned this lesson about half a year ago,.. and I learned it the hard way :( )

One way to create a Singleton that will also work with more than one ClassLoader is to use an enum. You will lose the advantages of polymorphism at this point (since enums have a private constructor, thus are final) but you will have a real Singleton in every situation.

However, the Singleton as you described it above works really well most of the time for most people in most projects. Just make sure you know how many ClassLoaders are present in your system.

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1