The Singleton Pattern Ensure a class only has one instance, and provide a global point of access to it.For example ,if we need a connection to single database at one time or when ever we are referring to to single application.properties file in struts application for showing application in one language at one time.Then we can need of singleton pattern or 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.
Need of Singleton Pattern –
- Sometimes we want just a single instance of a class to exist in the system
- We need to have that one instance easily accessible
- And we want to ensure that additional instances of the class can not be created
Benefits of Pattern –
- Controlled access to sole instance
- Permits a variable number of instances
How we can Implement singleton pattern-
We will be using statis method to call the client to get a reference to the
single instance and we’ll use a private constructor
/* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
public class VinaySingleton {
private static VinaySingleton VINAYINSTANCE ;
private VinaySingleton() {
}
public static VinaySingleton getInstance() {
if(VINAYINSTANCE ==null){
VINAYINSTANCE = new VinaySingleton();
}
return VINAYINSTANCE;
}
We will be having private constructor which tells that no other outside classes can directly instantiate this class. The only way to get a reference to the VinaySingleton object is to make a call to the static method VinaySingleton.getInstance ().Similarly create Myconnection class and method as above
Even if client call the VinaySingleton.getInstance multiple time the multiple object will point to same reference.
package techartifact.pattern.singleton;
public class VinayClient {
public static void main(String[] args) {
VinaySingleton i1 = VinaySingleton.getInstance();
MyConnection i2 = MyConnection.getInstance();
if (i1 == i2){
System.out.println("Both the object pointing to same reference");
}else{
System.out.println("Objects are not equal");
}
}
}




KARTHIK
hi
How does single-ton pattern work in case of Cluster Env ….
Does the object is still single for case of Distributed hosting ?
Can u Explain the same …..:{
The Singleton
You are missing two important points here.
1) You could still clone the instance retrieved through getInstace()
2) If you have more than one ClassLoader (which is not as uncommon as one might think), your Singleton-Class may be loaded more than once, each with its own field to store the instance. That means, with n ClassLoaders, you can have up to n _different_ instances.
One way to circumnavigate these issues is to use an enum to store the instance.
Java bug
@Karthik
I think you pointed you out a good question. In case of multiple JVM’s each JVM will have its own copy of objects.
Clustering across JVM in achievable using Custom API and 3rd party tools. Webpshere, and weblogic has provided different service to offer singleton objects in cluster.
http://download.oracle.com/docs/cd/E12840_01/wls/docs103/cluster/service_migration.html#wp1051458
http://publib.boulder.ibm.com/infocenter/wxdinfo/v6r0/index.jsp?topic=/com.ibm.websphere.xd.doc/info/WPF51/cwpfsingletonpattern.html
vinay
If you want to make sure that your singleton is a singleton even when it is passed around to different JVMs(this obviously means that your class is Serializable or Externalizable), then you must provide a method readResolve() in your singleton.
More on this method -
http://download.oracle.com/javase/1.3/docs/guide/serialization/spec/input.doc6.html
Eric Jablow
If you really need a singleton, you can use Joshua Bloch’s suggestion from Effective Java, 2nd edition:
public enum SystemSingleton {
INSTANCE;
public void addSystemListener(SystemListener l) {}
}
On the other hand, do you really need a singleton? Can you just construct an instance with singleton scope with your favorite DI framework?
saad khawaja
In the example above lines 13-15 are unnecessary in getInstance(), you already have done the initialization statically.
Shaaf
Good illustration. You don’t need to reconstruct in the getInstance() simply returning VINAYINSTANCE will do the job.
Also as your constructor doesn’t have anything inside it, makes life much more easier.
matt
Your Example is still not working:
If you make the static field final, you’ll have to instantiate it immediately:
private static final VinaySingleton VINAYINSTANCE = new VinaySingleton(). The current code above will not compile.
Personally, I would not go for the lazy initialization in any case. If you need a singleton to be there, you can instantiate it immediately. If you don’t it won’t be there in any way. If your application does never refer to VinaySingleton, the VM will not look at that class in any case. So there is some lazy instantiation going on inside the VM in any case.
URA
for multithreading environmenst you should have read already:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Nir Alfasi
There’s also an option of implementing a singelton using Static class – google it for more info.
Ramita
Singleton pattern is a simple and nice pattern but it causes a lot of problems in multi-threaded and distributed applications. For example, if you have two threads accessing the same database connection and trying to save some changes simultaneously, the updated data in the database may be corrupt. So extra care should be taken in implementing this pattern.