Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How many ways we can write Singleton Class in Java?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2014/04/23
Maria Thomas
by Maria Thomas , Tech Lead , J P Morgan Chase

There are four known ways to write Singleton class in Java.

1. The classic often used one : Create a private constructor and call this inside getInstance() method which is then invoked by the calling class. This should be synchronized using double checked locking. This comes in lazy initialization since the instance is created only when the method is first called.

2. Create a public static final field for the Singleton instance and call the constructor. This is created during class loading. This comes under early initialization.

public static SingletonInstance instance = new SingletonInstance();

3. Using Enums

Eg: public enum Singleton{ INSTANCE }

4. Creating static inner class wherein creation of the instance is done. This is called Singleton Helper model.

Eg:

public class SingletonInstance{

      private SingletonInstance(){}

      private static class SingletonHelper{

          private static final SingletonInstance instance = new SingletonInstance();

      }      

      public SingletonInstance getInstance(){

         return SingletonHelper.instance;

      }

}

More Questions Like This