Singleton Design pattern examples in java

Singleton design pattern in java

Maintaining a single instance of an object in a system is called single design patterns.

When we use the new Object() code to construct an object, one new instance is created; however, if we call these, several instances are created in heap memory. If the number of calls to new objects increases, the size of the object in heap memory grows, causing performance overhead.

To prevent this, we’ll create a single object for all calls and return the same object.

Simple singleton Implementation:-

  • private constructor to instantiate this class within this class only. not outside
  • a private static variable that is an instance of the same class
  • Declare Static method which checks static variable, if null, create an object else return the object.

Eager loading singleton example

But, There are multiple ways that can be written to load eager or lazy loading

public class Singleton {
 /*
  * Initializing the static member variable as null
  */
 public static Singleton single = null;

 /*
  * private means, we can not create an object using a new operator outside
  * this class
  */
 private Singleton() {

 }

 /*
  * This method always returns the same instance. you can make this method as
  * synchronized to create a multiple instances by different thread at a time
  */

 public static Singleton getInstance() {
  if (single == null) {
   single = new Singleton();
  }
  return single;
 }

 /*
  * clone is not supported and throws an exception if we make the clone of this
  * object
  *
  * @see java.lang.Object#clone()
  */
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "This is singleton class, cloning is not supported");
 }

 public static void main(String args[]) {
  /*
   * calling the multiple getInstance methods always returns the same
   * instance
   */
  System.out.println("Object=1 " + getInstance());
  System.out.println("Object=2 " + getInstance());
 }
}

Lazy Initialization singleton example

The singleton class is generated and initialized lazily in this case, which means that whenever the client calls the getInstance method, it creates a single object and returns it.

public class SingletonClass {

    private static class Loader {
        static SingletonClass object = new SingletonClass();
    }

    private SingletonClass () {}

    public static SingletonClass getInstance() {
        return Loader.object;
    }
}

All the above examples, returns a single instance per thread, Then how to create a single object in multi-threaded applications.

Singleton thread-safe example

The Synchronize keyword is used and named in multiple thread applications in this case. When one thread enters the synchronized block, it is allocated a lock, and another thread waits for the task of finishing the first thread.

This way, We can achieve a single object in multiple threads accessing the creation of an instance

public class Singleton {

private static Singleton instance = null;
privat e Singleton() {}

public static Singleton getInstance() {
        if (instance == null) {
                synchronized (Singleton.class) {
                        if (instance == null) {
                                instance = new Singleton();
                        }
                }
        }
        return instance;
}

Advantage

This pattern maintains one instance of java object in the heap memory of the java virtual machine instead of creating multiple instances. thus, Improve the performances and fewer objects created for heap memory