Singleton Design Pattern in Java

How to Use Singleton Design Pattern in Java

Singleton design pattern in Java is a creational design pattern that assures that simply one object of its kind exists and gives a single point of access to it for any additional code.

It is a combination of rules and programs and has similar benefits and drawbacks as global variables.

Java is an object-oriented programming language, it has been one of the most popular programming languages for several years. But, it is not regarded as pure object-oriented as it offers support for primitive data types like char, int, etc.

Java utilizes design patterns as solutions for most commonly and frequently occurred problems when designing software. Singleton Pattern is one such design pattern used by Java.

It is very useful yet disrupts the modularity of the code. You can utilize this model framework to restrict the number of instances of a class that can be built in the JVM (Java Virtual Machine).

Using this model, it can be assured that there exists only a single class instance.

After looking at the description you will see that it has a pretty simple design pattern but when it comes to implementation, it has a lot of implementation concerns.

Furthermore, the implementation of the Singleton pattern in Java has always been a debatable subject amongst developers.

Now, we will discuss Singleton Design Pattern in Java with all scenarios, different approaches for implementing Singleton design patterns, and some of the most reliable practices for its usage along with some related concepts.

Sometimes, there is a need for classes to own exactly one instance.

There are several circumstances when we want only one instance of the object and instantiating more than one instance, will make you run through all kinds of problems like overuse of resources, wrong program behavior, or inconsistent results.

Singleton Pattern states that simply “define a class that owns only one instance with a global point of access to it”. In other words, a class ensures only a single instance and single object can be utilized by all other classes.

You can’t simply utilize a class that depends on Singleton in some other connection. You will have to move the singleton class as well. Many times, this limitation occurs throughout the generation of unit tests.

But, the singleton pattern is one of the most simplistic design patterns in Java. This kind of design pattern appears within a creational pattern as this pattern gives one of the most reliable ways to build an object.

Singleton Design Pattern in Java

  • Singleton design pattern Java illustrates the instantiation of a class and assures that only one instance of the class exists.
  • Singleton design pattern Java is utilized for drivers’ objects, logging, caching, and thread pool.
  • The singleton class needs to provide a global access point to get the instance of the class.
  • Singleton design pattern is further utilized in different design patterns like Prototype, Builder, Abstract Factory, Facade, etc.
  • Singleton design pattern Java is practiced in core java classes, for example, java. awt.Desktop, java. lang.Runtime, etc.

Purpose of Using a Singleton Class Function 

One of the main objectives that a singleton class has is to reduce the number of entities that would be produced to only one. This ensures that access to components, such as a database connection or socket, is managed.

There is no memory space loss while using a singleton class as it limits instance creation. This object would be generated once rather than whenever the latest proposal is submitted.

This single object can be utilized multiple times depending on the needs. This is the reason why the Singleton design in Java is generally used in multi-threaded and database operations for debugging, cache, security configurations, and thread pools.

Singleton Class Design 

If you need to style a singleton class, you need the following:

  • The use of a private keyword to demonstrate the Singleton class’s constructor. You need to declare it as private so that no additional classes can utilize it to build or instantiate objects.
  • A class with a private variable; appears to be the only class with instance type.
  • Create a static main function with the return type as the singleton class’s objects.

Singleton Class

Singleton design pattern Java restricts a class to create multiple objects so you can build only one instance of the singleton class. Singleton classes are utilized for caching, logging, database connections, and thread pool, etc. There are many ways to build a singleton but it has some basic steps:

  • Make a constructor private: You should make the constructor private so you cannot build an instance of a class from outside of the class.
  • Provide a static method to obtain the object of a singleton class: Build the static method which will return an object of the singleton class.
  • Construct an instance of the same class as public static which will be returned by the static method.

 

Also, Read – Top 19 Git Commands with Examples

 

Implementation of Singleton Design Pattern in Java

There are several ways to implement or design a Singleton class. The following are some popular methods by which we can design a Singleton class or you can say different forms of singleton design patterns:

How to Use Singleton Design Pattern in Java infographic

1) Eager Instantiation

Here we will create an instance of Singleton with the help of a static initializer at load time. JVM executes static initializer when the class is loaded and therefore this is assured to be thread-safe.

Utilize this method simply when the Singleton class is utilized during the execution of the program.

public class Singleton implements Serializable {

private static Singleton singletonObject = new Singleton();

// Attaching a private constructor so that no one builds an object with the new operator

private Singleton() {

  }

  public static Singleton getInstance() {

    return singletonObject;

  }

}

2) Lazy Instantiation

Here in this method, we declare getInstance() as static so that it can be called without instantiating the class.

When the getInstance() method is called for the first time, it creates a new Singleton object and later it only returns the same object reference. The primary problem with this method is that it is not thread-safe.

public class Singleton implements Serializable { 

private static Singleton singletonObject; 

// Adding a private constructor so that no one creates an object with a new operator private Singleton() {

} 

public static Singleton getInstance() { 

if (singletonObject == null) { 

singletonObject = new Singleton(); 

} 

return singletonObject; 

} 

}

3) Using Static Block

This method is a sub-part of Eager initialization. The only distinction is that an object is built in a static block so that we can have access to its creation, such as exception handling. The object is built at the time of class loading.

// Java code to create a singleton class

// Using Static block

public class GFG

{

  // public instance

  public static GFG instance;

  private GFG()

  {

    // private constructor

  }

static

  {

    // static block to initialize instance

    instance = new GFG();

  }

}

 4) Thread Safe Singleton

A more convenient way to create a thread-safe singleton class is to build the global access method synchronized to make one thread execute this method at a time. The general implementation of this strategy is like this:

package com.journaldev.singleton;

public class ThreadSafeSingleton {

private static ThreadSafeSingleton instance;

private ThreadSafeSingleton(){}

public static synchronized ThreadSafeSingletongetInstance(){

if(instance == null){

instance = new ThreadSafeSingleton();

}

return instance;

}

}

5) Using Reflection to Destroy Singleton Pattern

Reflection can be utilized to annihilate all the above singleton implementation strategies.

package com.journaldev.singleton;

import java.lang.reflect.Constructor;

public class ReflectionSingletonTest {

    public static void main(String[] args) {

        EagerInitializedSingletoninstanceOne = EagerInitializedSingleton.getInstance();

        EagerInitializedSingletoninstanceTwo = null;

        try {

            Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();

            for (Constructor constructor : constructors) {

                //Below code will destroy the singleton pattern

                constructor.setAccessible(true);

                instanceTwo = (EagerInitializedSingleton) constructor.newInstance();

                break;

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        System.out.println(instanceOne.hashCode());

        System.out.println(instanceTwo.hashCode());

    }

}

Singleton Class Differences with Normal Class

A singleton class differs from other classes when it comes to the method of instantiating the class’s entity. Java constructors build a standard class.

Furthermore, if you want to initialize a class object of singleton type, you should utilize the getInstance() function. A general class disappears into the terminal of an application’s lifecycle whereas a singleton class does not.

 

Also, Read – Top 10 Tech Start-up Business Ideas to Look in 2021

Conclusion

Here we have learned all regarding Singleton Design Pattern in Java with different scenarios. We have noticed that a Singleton class has simply one item in it.

You can build a Singleton utilizing private constructors and the getInstance constructor function.

We hope that now you are clear with how to create a singleton design pattern Java utilizing eager and lazy loading techniques along with other techniques.

You will also learn here the differences between a normal class and a singleton class. Happy coding!