Multiple Singleton Design pattern examples in java


Singleton design pattern in java

Maintaining a single instance of an object in a system is called as 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 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 any object using new operator outside
  * this class
  */
 private Singleton() {

 }

 /*
  * this method always return same instance. you can make this method as
  * synchronized to create amultiple isntances by different thread at a time
  */

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

 /*
  * clone is not supported and throws 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 method 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 initialised 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 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 synchornize block, it is allocated a lock, and another thread is waited for the task of finishing the first thread.

This way, We can achieve single object in multiple thread accessing the creation of 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 heap memory of java virtual machine instead of creating multiple instances. thus, Improve the performances and fewer objects created for heap memory

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.