Thursday, October 10, 2019

How to create singleton object and how to make it thread safe?

Singleton class is a class which can have only one object at a time.

Restriction/avoid to create the multiple object. Single object can be used over the application.

We can restrict/avoid to create a object of class from other class, we can achive by setting constructor private.

/**
 *
 */
package com.learn.java.thread;

/**
 * @author palrajb
 *
 */
public class SingleTon {

    private SingleTon() {
       
    }

}


If we made constructor private, then what is the use of class and how it will going to be used in application.

Give public static factory method to create instance

public static final SingleTon objectSingleTon = new SingleTon();

its looking good, but its getting eagerly initialized, if nobody used this variable then we are created unused object??!!

Let make it lazt initialize,

public class SingleTon {

    public static SingleTon objectSingleTon = null;

    private SingleTon() {

    }

    public static SingleTon createObject() {

        objectSingleTon = new SingleTon();

        return objectSingleTon;

    }

}


Its always better do null check before object creatation is good practice.

public static SingleTon createObject() {

        if (objectSingleTon == null) {

            objectSingleTon = new SingleTon();

        }

        return objectSingleTon;

    }

   
Above logic is works perfect for single thread enviroment. If multiple thread is trying to create the object, first thread is checking object is null and creating object, at this time    next thread checks object null , yes instance is null so it will come to next line and create object so totally two object ??? . Do avoid this we can use synchronised key.


public static SingleTon createObject() {
        if (objectSingleTon == null) {
            synchronized (SingleTon.class) {
                if (objectSingleTon == null) {

                    objectSingleTon = new SingleTon();

                }
            }
        }
        return objectSingleTon;
    }


Its always better to have double check the object null.

No comments:

Post a Comment