2 Mar 2012

Singleton Class

A Singleton class is an implementation of a Singleton Design Pattern. This design pattern states that a singleton class has only one instance and provide global way to access it..But at same time it also allow  flexibility to creating more instances if needed.  Such a class can be used for creating the database connection java.lang.Runtime is an example of a singleton class
So how can this pattern can be implanted in java ?  There are different ways to implement a singleton class , in this post i'll discuss two implementation techniques.


The most common technique is to create a singleton class which have 
  •  a private static field which is a reference to a singleton object, 
  •  a static method which returns the singleton object and 
  • a private no-arg constructor which prevent any instance being created.
Whenever a class is loaded static field are assigned only once. Therefore a instance can be created at loading time by assigning a newly created ob object to static filed.

Listing 1


In another technique the instance can be created in lazy fashion. Instead of creating a instance of singleton class at loading time , it can be created on demand.


Listing 2



When first time  getSingletonInstance() is called if(obj==null) condition results true thereby a new object of singleton class is created and its reference is stored in static field obj. If  getSingletonInstance() is called again , if(obj==null) condition results false.Thereby returning same instance which was created on first call.
In next part i'll discuss few issues related to the singleton class which must be considered when implementing singleton class.




When a Singleton is not a Singleton
Multiple instance of singleton may be created if synchronization is neglected. For example if one threads invokes the constructor and simultaneously another thread calls the getSinletonInstance() method , then there will be two instance of a singleton class. That is why synchronized keyword is used in method signature.


When multiple instance of singleton is needed, then singleton class should have a default constructor so that it can be subclassed by other class.Then this sub class may provide a public constructor allowing anyone to make instance of a singleton class.


Two different class loaders used to load a singleton class will have two different instance of a singleton class.The different class loader have different namespace that distinguish classes , even though class name are same.


When a singleton object is serialized  it must be ensured that only one  ObjectOutputStream object  is used for serialization.If  ObjectOutputStream is closed or reset , then there will be two distinct instance of a singleton class.




That's all on Singleton class. Hope you find it useful.


No comments:

Post a Comment