Singleton – What it is and why is Singleton ?
Apr 24th, 2009 | By admin | Category: JavaSometimes it’s the requirement of the application to maintain only one instance of a class . This instance will be accessed throughout the a software life cycle of the application.This type of classes are called Singleton class.
Typical examples could be ,Logger,Print spoolers,Connection pool etc.
Singleton is ideal if an application developer wants to make sure only one instance of the class should be created. Give a global point of access to the object of the class.
Follow the code below,
package com.etechguide.java.classtype;
public class SingleTon {
private SingleTon() {
// Not doing anything
}
static private SingleTon instance = null;
/**
* @return the unique instance.
*/
static public SingleTon getInstance() {
if(instance == null ) {
instance = new SingleTon();
}
return instance;
}
}
Here I have provided a default private constructor,
private SingleTon() {
// Not doing anything
}
and then provide a way to one point global access,
static public SingleTon getInstance() {
if(instance == null ) {
instance = new SingleTon();
}
return instance;
}
The above SingleTon Class should be improved to make the access method Synchronized to prevent thread Problems.This can be achieved as,
public static synchronized SingleTon getInstance()
But are we safe here ? No. we can still create a clone of the object using,
SingleTon ston = (SingleTon)obj.clone();
We should override the clone method so that an attempt of cloning the object resulted in an exception , say CloneNotSupportedException Exception.
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Full version of the SingleTon Class is ,
package com.etechguide.java.classtype;
public class SingleTon {
private SingleTon() {
// Not doing anything
}
static private SingleTon instance = null;
/**
* @return the unique instance.
*/
public static synchronized SingleTon getInstance() {
if (instance == null) {
instance = new SingleTon();
}
return instance;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
Single instantiation of the class can be done in the following way too,
public class SingleTon {
private static SingleTon instance = new SingleTon();
public static SingleTon getInstance() {
return instance;
}
private SingleTon() {
}
}

Post Java-5 double checking issues have been resolved, so you can check if the value is currently null and then check it again in a synchronized block (in 1.4 and earlier there was a subtle bug that prevented this from being 100% reliable)
if (so and so ==null({
synchronized{
if (so and so ==null({ …