Friday, June 3, 2011

SingleTon Pattern Nots / Key Points

Some of the key points which I feel one should know.


1) Constructor must be private as nobody should able to create object.

2) getInstance method must be static

3) getInstance method must take care of multiple threads

4) if you make getInstance method as synchronized then it will hamper the performance, Use synchronized block

5) Class should not support serialization, as serialization can create multiple object

6) Class should not be clonable, as cloning can create multiple objects

7) Even if you do synchroniz the piece of code in getInstance() then, still you will have to do double check looking.

 

in the below code that getInstance method ensures that only one instance of the class is created. The constructor is not accessible from the outside of the class , only way of instantiating the class would be only through the getInstance method.


Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.


class MySingleton
{
private static MySingleton instance;
private MySingleton()
{
// Empty constructor which is private
}

public static synchronized MySingleton getInstance()
{
if (instance == null)
instance = new MySingleton();

return instance;
}
}

Where can you use Singleton pattern

 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are ussualy implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application.  

3 - Accesing resources in shared mode

It can be used in the design of an application that needs to work with the serial port.  In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

4 - Factories implemented as Singletons

Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

 

There are two ways to create singleton classes




Lazy instantiation using double locking mechanism.

                The standard implementation shown in the above code is a thread safe implementation, but it's not the best thread-safe implementation beacuse synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for syncronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any syncronized block. This optimization consist in checking in an unsynchronized block if the object is null and if not to check again and create it in an syncronized block. This is called double locking mechanism.

Early instantiation using implementation with static field

                In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don't need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.

Singleton - A simple example (java)

//Early instantiation using implementation with static field.
class Singleton
{
private static Singleton instance = new Singleton();

private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}

public static Singleton getInstance()
{
return instance;
}

public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}
================================================
What are disadvantages of Singleton Pattern
================================================
Disadvantages:


  • 1) Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
  • 2) Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • 3) Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
  • 4) Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.
 
 
Fact about SingleTon


1) if your singleTOn class implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.


2)SingleTon Class is not thread safe


if(instance == null) {
    instance = new Singleton();
}


3) if you clone singleTon class, it will create a clone and there will be two different object  will be created. You can print hashCode of each instance, it will be different


4) if you create synchronized method, it will always hit the performance whenever you
you create object.


public synchronized static Singleton getInstance() {
   if(singleton == null) {
      synchronized(Singleton.class) {
         singleton = new Singleton();
      }
      System.out.println("Object created");
   }
   return singleton;
}


5) if you creat synchronized block, its not thread safe. Suppose control comes to
System.out.println("Object created"); statement and before returning 2nd thread come
here thread1 is out of synchornized block and again thread2 can enter block


public static Singleton getInstance() {
   if(singleton == null) {
      synchronized(Singleton.class) {
         singleton = new Singleton();
      }
      System.out.println("Object created");
   }
   return singleton;
}

No comments:

Post a Comment