×

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration.

It can also be defined in another way, a class must make sure that only one instance is produced and that only one object can be utilized by all other classes.

This particular design pattern falls under the category of a creational pattern because it provides one of the simplest ways to make an object.

Use of Singleton Pattern Design

This pattern design is mainly used to create the object such that only one object is created for a class and this class provides the technique of retrieving the class's unique object, removing the need to create it first.

This singleton pattern is also used in applications that involve datasets and multiple threads frequently

It is involved in the configuration files or specifications, threaded pools, caching, and logging, among many other things.

Implementation of Singleton Pattern Design

It implemented in three steps, such as:

  1. Make a Singleton Class first.
  2. Take the sole instance of the singleton class's object.
  3. Check the results.

There will be just one object class created. The static instance of the SingleObject class as well as the private function Object() [native code] are both available.

The SingleObject class offers a static method to return its static instance to the outside world.Our demo class, SingletonPatternDemo, will use the SingleObject class to obtain a SingleObject object.

Types of singleton pattern design

There are two types of singleton pattern design

  • Early instantiation
    • Using static block
  • Lazy instantiation
    • Thread Safe Singleton
    • Lazy initialization with Double check locking
    • Bill Pugh Singleton Implementation

Early instantiation

In short, it is defined as the process of instance creation when loading or at a load time.

This is considered to be the simplest method for developing a singleton time up ahead. An object of that class is created when the JVM loads the class into memory.It is accomplished by directly assigning an instance's reference.

When a computer will always use an instance of this class or when constructing an instance didn't accept up a lot of time or resources, it can be used.

Example

// Early Initialization
public class Early
{
  private static final Early instance = new Early();
  private Early()
{
//private constructor
}
 public static EalrygetInstance()
    {
        return instance;
    }
}

Using static block

This static block is the sub-part of the early instantiation or initialization.

The main difference is that objects are again created in static blocks so that we may access them immediately after they are created and handle exceptionsSimilarly, when a class is loaded, an object is produced.

// using static block
import java.io.*;
public class Sb
{
  public static Sb instance;
 private Sb()
  {
    // private constructor
  }
static
  {
    instance = new Sb();
  }
}

Advantages of Early instantiation

  • extremely easy to use.
  • certainly wastes resources. because whether or not it is necessary, a class instance is always produced.
  • Instance creation that is not necessary wastes CPU time as well.
  • There is no way to handle exceptions.

Lazy instantiation

In short, it is defined as the process of instance creation when needed

Going into it, here the object is created only when it is necessary.It is required to implement the method called asgetInstance(), which returns the instance. There is a null check that, if true, creates the object; else, it returns the one that has already been constructed.

The constructor is made final to ensure that the class cannot be created in any other way. Because objects are generated within methods, it is guaranteed that they won't be produced until and unless they are needed. To prevent direct access, instances are kept private.

The source wastage is prevented by this initialization method

Example

// With Lazy initialization
public class Li
{
  private static GFG instance;
  private Li()
  {
    // private constructor
  }


  public static Li getInstance()
  {
    if (instance == null)
    {
      // if instance is null, initialize
      instance = new Li();
    }
    return instance;
  }
}

Thread-safe singleton

Creating a thread-safe singleton allows for the preservation of singleton properties even in multithreaded environments. A singleton class is made thread-safe by synchronizing the getInstance() method so that multiple threads cannot access it simultaneously.

Example

public class Thread
{
 private static Thread instance;
 private Thread()
  {
    // private constructor
  }
  synchronized public static Thread getInstance()
  {
    if (instance == null)
    {
      instance = new Thread();
    }
    return instance;
  }
}

Advantages of Lazy instantiation

  • Only when it is necessary is an object created.
  • It is also feasible for methods to handle exceptions.
  • Each time, the null condition must be verified.
  • No direct access is possible to instance.

Real-time Example for single pattern design in java

class Singleton
 {
private int n = 20;
private Singleton() 
{
}
private static class Helper {
private static final SingletonuniqueInstance = new Singleton();
}
public static Singleton getInstance() {
return Helper.uniqueInstance;
}


public int getNum() {
return n;
}


public void setNum(int n) {
this.n = n;
}


}


public class SingletonDemo {
public static void main(String args[]) {
Singleton singleInstance = Singleton.getInstance(); // first instance of the class
singleInstance.setNum(25);
Singleton secondInstance = Singleton.getInstance(); // second instance of the class
System.out.println(secondInstance.getNum()); // trying to get the class variable using getter method
}
}

Related Topics

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.