Java @ Desk: Design patterns | Java at your desk

Double Locking in Singleton Pattern in Java



Double Locking in Singleton Pattern in Java

In one of earlier posts, we learned Singleton design pattern in java & Singleton Design Pattern Without Cloning Java.


There is one more issue in this block of code that will come up in a multithreaded environment. In the below code, Thread.sleep is explicitly used in order to test the violation in multithreaded environment


public static SingletonDoubleLocking getSingletonDoubleLocking() {
  if (singletonDoubleLocking == null) {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   singletonDoubleLocking = new SingletonDoubleLocking();
  }
  System.out.println("SingletonDoubleLocking - "
    + singletonDoubleLocking);
  return singletonDoubleLocking;
 }


Consider above code, where a method will be called in a multithreaded environment and so multiple threads enter the block and creates multiple instances which will violate the principal of Singleton Design Pattern as shown below :
package com.doubleLock;

public class ClientSingletonDoubleLocking implements Runnable {

 public static void main(String args[]) {
  ClientSingletonDoubleLocking clientSingletonDoubleLocking = new ClientSingletonDoubleLocking();
  int length = 5;
  Thread[] thread = new Thread[length];
  
  for (int index = 0; index < length; index++) {
   thread[index] = new Thread(clientSingletonDoubleLocking);
  }
  
  for (int index = 0; index < length; index++) {
   thread[index].start();
  }
 }

 @Override
 public void run() {
  SingletonDoubleLocking singletonDoubleLocking = SingletonDoubleLocking
    .getSingletonDoubleLocking();
 }
}


To avoid so, we need to perform a double locking to ensure no 2 objects are created in multithreading environment as shown below:
public static synchronized SingletonDoubleLocking getSingletonDoubleLocking() {
  if (singletonDoubleLocking == null) {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   singletonDoubleLocking = new SingletonDoubleLocking();
  }
  System.out.println("SingletonDoubleLocking - "
    + singletonDoubleLocking);
  return singletonDoubleLocking;
 }

In the above implementation we are synchronizing the static method which is a lock on an Class object. This will ensure only one thread will enter the synchronize method

Singleton Pattern Java With Double Locking and Without Cloning

Singleton Pattern Java With Double Locking and Without Cloning
In our last post we have seen how to apply double locking for singleton object creation so that multiple threads do not enter the method and instantiate the object. Refer Double Checked Locking in Singleton.

We also must prevent object creation using the cloning of objects. So we must ensure that the singleton class must override the Object clone() method and throw the Exception in that.

Complete example of Singleton with Double Locking and without cloning as shown below. Thread.sleep is just for the demo purpose. Just to understand the flow as our memory does not work as fast as JVM :)

package com.doubleLock;

public class SingletonDoubleLocking {

 private static SingletonDoubleLocking singletonDoubleLocking = null;

 private SingletonDoubleLocking() {

 }

 /** 
  * synchronized so that multiple thread do not enter the method
  * @return SingletonDoubleLocking
  */
 public static synchronized SingletonDoubleLocking getSingletonDoubleLocking() {
  if (singletonDoubleLocking == null) {
   System.out.println("Object is null");
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   singletonDoubleLocking = new SingletonDoubleLocking();
  }
  System.out.println("SingletonDoubleLocking - "
    + singletonDoubleLocking);
  return singletonDoubleLocking;
 }
 /**
  * Override clone method so that clone is avoided
  */
 @Override
 public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Thrown this exception in order to avoid the creation of copy of this object");
    }
}


Client file to test the double locking and cloning


package com.doubleLock;

public class ClientSingletonDoubleLocking implements Runnable {

 public static void main(String args[]) {
  ClientSingletonDoubleLocking clientSingletonDoubleLocking = new ClientSingletonDoubleLocking();
  int length = 5;
  Thread[] thread = new Thread[length];
  
  for (int index = 0; index < length; index++) {
   thread[index] = new Thread(clientSingletonDoubleLocking);
  }
  
  for (int index = 0; index < length; index++) {
   thread[index].start();
  }
 }

 @Override
 public void run() {
  SingletonDoubleLocking singletonDoubleLocking = SingletonDoubleLocking
    .getSingletonDoubleLocking();
 }
}


Output
Object is null
SingletonDoubleLocking - com.doubleLock.SingletonDoubleLocking@18a992f
SingletonDoubleLocking - com.doubleLock.SingletonDoubleLocking@18a992f
SingletonDoubleLocking - com.doubleLock.SingletonDoubleLocking@18a992f
SingletonDoubleLocking - com.doubleLock.SingletonDoubleLocking@18a992f
SingletonDoubleLocking - com.doubleLock.SingletonDoubleLocking@18a992f

As shown above inside a null check it enters only once even though the 5 threads have been started.

In order to check how cloning works put this blok of code in the client file run method and run the file again.
try {
   SingletonDoubleLocking singletonDoubleLocking2 = (SingletonDoubleLocking) singletonDoubleLocking.clone();
  } catch (CloneNotSupportedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }


Facade design pattern in java

Facade is design pattern in java that helps to re design a poorly structured API into a well defined API. It provides a simpler interface to the client, but internally it interacts with complex components and get a job done for the client. It hides a complexity behind exposing a simpler interface to the client.

Consider a scenario, of an Employee Hiring consultancy that collects all the information of an employee going to join in some company. The information includes personal details, last employment details, last drawn salay, expected salary, desired location.
Now, lets say, there are different complex interfaces, one that returns employee personal information, one give employee past experience details and so on.
So, in this case, if a client need a complete list of information of one particular employe, there needs to give a call to lots of other interface.

Proxy design pattern in java

Proxy, as the name suggest, does the work what the real one should do. Proxy is some thing that performs the task what the real java object must perform to do.Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.

Why to use proxy?
There can be many instances, where real object wants the task to be performed by the proxy object. In this case, proxy first checks if the real instance object is available or not. It not create the new instance but if the object is already available, do not create the new instance, proxy instance will be used to perform the operation.

Decorator design pattern in java

As the name suggest, it decorates some basic behaviour of an object. It is used to extend the behaviour of certain object. In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.

Use decorator pattern, to add responsibility to objects without affecting other objects.

Adapter design pattern in java

The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter.

There is a SalaryCalculator.java class file which takes employeeId and annualPackage fields as input and returns the monthly inhand for that employee.

Prototype design pattern in java

Prototype pattern is used where the application needs many instances of an same object with minimal changes. Hence the Cloneable interface is used in this where the clone of the object is returned.

Question arises why clone, why not new object creation if many instances are required?

In general, cloning or creating an object using new operator are same. But there are cases where new object creation would be heavy in cases where a constructor for an object does some heavy provessing. Say for example, creating a database connection. In this case, cloning would be much much cheaper.

Builder design pattern in java

This design pattern breaks the complex object creation into simpler processes. The construction process remains the same to create different representations. Director controls the construction of the object and only the director knows what type of object to create.

This pattern helps the object creation in a step by step manner. It breaks the module into smaller pieces and the smaller pieces in integration gives the complex object.

Factory Pattern in java

In factory design pattern, there is a factory java class that hides the object creation from outside world. In this pattern, the object creation depends on the data passed as an argument to the factory class and the factory class decides based on the argument passed, object of which class needs to be instantiated and returned.

This pattern provides abstraction or interface implementation and the factory class generally creates an object of subclass and returns the same.

Consider a simple scenario of IT industry where employees from IT team gets a variable payout every year where other departments like HR or Admin does not get.

Design pattern in java

What are design patterns?

Answer: Design pattern is a strategy to use to build up a web application. It helps in designing of an application that will be more flexibility, easy to maintain, etc. Design Patterns also solve specific programming challenges regarding usability and maintainability.

In some other cases, the pattern is also a way to deal with "inefficiencies" of the language, where "inefficiency" is very broad in its meaning, and not always in a bad term.

Singleton Design Pattern Without Cloning Java

Issues with basic version of Singleton pattern design:
1) It could happen that SingletonPattern.getSingletonPatternObject() call may occur from 2 different places in an application at the same time and 2 objects get created which will violate the principal of the pattern

2) Consider the code
SingletonPattern clonedSingletonPattern = (SingletonPattern) obj.clone();
This code will create the copy of the singleton object which again violates the design patters implementation

Click Singleton Pattern Java With Double Locking and Without Cloning for complete version of Singleton Design Pattern

To avoid above issues here is an improved version

public class SingletonPattern {

    // Make the constructor private so that it cannot be instantiated outside the class
    private SingletonPattern() {

    }

    // Variable for SingletonPattern class
    private static SingletonPattern singletonPattern;

    // Method to get the instance of SingletonPattern class
    public static synchronized SingletonPattern getSingletonPatternObject() {
        if (singletonPattern == null) {
            singletonPattern = new SingletonPattern();
        }
        return singletonPattern;
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Thrown this exception in order to avoid the creation of copy of this object");
    }
}


Singleton design pattern in java

As the name suggests, Singleton patters allows only single instance of particular class throughout the application.

Why to create a Singleton class in an application?

Answer: Say for instance, an application wants to load a property class which contains a set of properties, and this property file is being used throughout the application. So a better way is to load that property file once and use it throughout.