×

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

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.