Galleries

Hash Map

HashMap is one of the most performing data structure in java collection framework. This provides constant time for both insertion and retrieval. This is used for large scale data since this is having high performance in insertion and retrieval. However this performance is depending on the two factors such as initial capacity and load factor. We can construct HashMap in four way and default constructor is having load factor is .75 and initial capacity as 16.

(more…)

Advertisements

Singleton Design Pattern

This is the pattern which ensures there will be only one instance of a class in JVM and it can be accessed via globally. Generally this pattern is used to be on caching, logging, settings and configurations and so on.

Static class has below properties such as : –

  1. Static Member – this keeps the instance of class.
  2. Private constructor – this avoids creating multiple instances from this class.
  3. Static public method – the only one instance can be accessed via globally through this method.

Below I am explaining lazy implementation of singleton design pattern which is not thread safe. But better to learn this implementation first and then we can learn how to make it thread safe.

Below is the lazy implementation of singleton design pattern.

public class SingletonDesignPatternLazyImplementation {

    //THIS STATIC OBJECT KEEP THE INSTANCE THAT ONLY ONE THIS CLASS IS GOING TO BE CREATED
    private static SingletonDesignPatternLazyImplementation singletonDesignPatternLazyImplementation;

    //THIS PRIVATE CONSTRUCTOR PREVENT ANY OTHER CLASS INSTANTIATING.
    private SingletonDesignPatternLazyImplementation(){

    }

    //THIS PROVIDE ACCESSIBILITY IN GLOBAL
    public static SingletonDesignPatternLazyImplementation getSingletonDesignPatternObject(){
        if(singletonDesignPatternLazyImplementation == null){
            singletonDesignPatternLazyImplementation = new SingletonDesignPatternLazyImplementation();
        }
        return singletonDesignPatternLazyImplementation;
    }

    public void print(){
        System.out.println("Hello here I am");
    }
}

This is how to use above implementation.

class TestSingleton{
    public static void main(String[] args) {
        SingletonDesignPatternLazyImplementation.getSingletonDesignPatternObject().print();
    }
}

Thread safe singleton design pattern implementation

Since singleton object is a static one it will store in the PremGen (permanent generation) in heap.
Previous example is not work with multiple threading environments since multiple threads can access same time and loop back and can destroy the singleton behavior. That is why we have to find a thread safe method to implement singleton design pattern. As the solution we are going to make global accessible method as synchronized. By that only one thread can access that method at a time.

public class SingletonDesignPatternThreadSafe {

    private static SingletonDesignPatternThreadSafe singletonDesignPatternThreadSafe;

    private SingletonDesignPatternThreadSafe(){

    }

    public static synchronized SingletonDesignPatternThreadSafe getSingletonDesignPatternThreadSafe(){
        if(singletonDesignPatternThreadSafe == null){
            singletonDesignPatternThreadSafe = new SingletonDesignPatternThreadSafe();
        }
        return singletonDesignPatternThreadSafe;
    }
}

This is pretty similar to lazy initialization but public method is synchronized only as the difference.
Java synchronizing is cost high when we consider performance of application. Therefore we can mention this implementation is bad when we consider about performance even though it secure singleton approach. To overcome this issue there is approach called “double checked locking” mechanism. What it does is adding synchronized block inside if condition of public method rather implementing public method as synchronized.
Check below example.

/**
 * Created by Dasun De Silva on 8/29/2017.
 */
public class SingletonDesignPatternThreadSafeDoubleCheckedLock {

    private static SingletonDesignPatternThreadSafeDoubleCheckedLock singletonDesignPatternThreadSafe;

    private SingletonDesignPatternThreadSafeDoubleCheckedLock(){

    }

    public static SingletonDesignPatternThreadSafeDoubleCheckedLock getSingletonDesignPatternThreadSafe(){
        if(singletonDesignPatternThreadSafe == null){
            synchronized (SingletonDesignPatternThreadSafeDoubleCheckedLock.class) {
                singletonDesignPatternThreadSafe = new SingletonDesignPatternThreadSafeDoubleCheckedLock();
            }
        }
        return singletonDesignPatternThreadSafe;
    }
}

Last method is the most suitable implementation for singleton design pattern as well as the performance. But still there is a memory problem since we are using synchronizing. So Bill Pugh has found a way to implement singleton design without using synchronizing but using static inner class. Check below example first then I will explain it.

package creational;

/**
 * Created by Dasun De Silva on 8/29/2017.
 */
public class SingletonDesignPatternInnerStatic {

    private SingletonDesignPatternInnerStatic(){}

    private static class Helper{
        private static final SingletonDesignPatternInnerStatic SINGLETON_DESIGN_PATTERN_INNER_STATIC = new SingletonDesignPatternInnerStatic();
    }

    public static SingletonDesignPatternInnerStatic getSingletonDesignPatternInnerStatic(){
        return Helper.SINGLETON_DESIGN_PATTERN_INNER_STATIC;
    }

}

Above example we do have not a static private member defined in parent class but in static inner class. This case it do not create member instance of parent class but only on request instance will be created. That means Helper class is not loaded until someone called SingletonDesignPatternInnerStatic method.

Enum as a singleton

package creational;

/**
 * Created by Dasun De Silva on 9/11/2017.
 */
public enum  SingletonEnum {
    INSTANCE;

    public void doStuff(){
        System.out.println("Enum using singleton hashcode = " + hashCode());
    }
}

class CallEnum{
    public static void main(String[] args) {
        SingletonEnum.INSTANCE.doStuff();
        SingletonEnum.INSTANCE.doStuff();
    }
}

Reference URL

http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
https://dzone.com/articles/singleton-design-pattern-%E2%80%93