×

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it.

Introduction

Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one of the best classes that exist in Java programming language. In this object-oriented programming language, Singleton is class, which means it can have only one object at a particular time or instance. After creating an instance of the class, other new variables can also point to that instance. Suppose we do any modifications with the new variables inside the class through any instance. In that case, it affects created instance and is visible if we access that new variable through any other variable of that class type defined.

Here are the few key points that must follow while creating or designing the singleton class

1.         Ensure that a constructor is private.

2.         Develop a static method which consists of a return type object of the singleton class. To develop this static method, we must know about lazy initialization.

Generally, there are two forms involved in the singleton design pattern,

  • Early Instantiation: the instance of the class (object) takes place at load time.
  • Lazy Instantiation: the creation of an instance of the class or object is done based on the requirements

Purpose of Singleton Class

The fundamental role of a Singleton class is to confine the restriction of the quantity of item creation to only one. This frequently guarantees access control to resources, for instance, database association.

The memory space wastage doesn't happen with the utilization of the singleton class since it confines the case creation. The instance of the class creation will occur just a single time instead of making it each time another solicitation is made.

We can utilize this single item over and over according to the necessities. This is why multi-threaded and database applications generally use the Singleton design in Java for reserving, logging, thread pooling, arrangement settings, and more.

For instance, there is a permit with us. We have just a single database association or assume on the off chance that our JDBC driver doesn't permit us to do multithreading, then, at that point, Singleton class comes into the image and ensures that at a time, only a solitary connection or a single thread can get to the association.

How to Design/Create a Singleton Class in Java?

To make a singleton class, we should follow the below key points:

1. Guarantee that only one instance of the class exists.

2. Give worldwide admittance to that instance by

•          declaring all constructors of the class to be private.

•          Giving a static method or strategy that returns a reference to the case. The apathetic statement idea is utilized to compose the static design.

•          The instance is put away as a private static variable.

Illustration of singleton classes is Runtime class, Action Servlet, and Service Locator. Confidential constructors and manufacturing plant techniques are additionally an illustration of the singleton class.

The contrast between Normal Class and Singleton Class

We can recognize a Singleton class from the typical classes for the method involved with starting up the object of the class. To start up a regular class, we utilize a java constructor. Then again, to launch a singleton class, we use the getInstance() strategy.

The other contrast is that a regular class disappears toward the finish of the lifecycle of the application while the singleton class doesn't obliterate the fulfilment of an application.

Execution:

Let us brief how the singleton class changes from the typical class in Java. Here the thing that matters is as far as launch concerning the regular type, we use constructor, while for singleton class, we use getInstance() technique which we will look out for in model 1 as portrayed underneath. As a rule, to avoid disarray, we may likewise utilize the class name as a strategy name while characterizing this technique, which will be displayed in example.

Advantages

  • Singleton controls concurrent access to the resource.
  • It ensures only one object is available across the application in a steady state.

Example of Singleton Class:

Let's create a singleton class.

SingletonEg.java
class Test  
{   
public static void main(String s[])   
{   
// instantiating Singleton class with variable a   
SingletonEg a = SingletonEg.getInstance();   
// instantiating Singleton class with variable b   
SingletonEg b = SingletonEg.getInstance();   


// changing variable of instance a  
a.str = (a.str).toUpperCase();   
System.out.println("String from a is " + a.str);   
System.out.println("String from b is " + b.str);   


}   
}   

Output:

IT IS AN EXAMPLE OF SINGLETON CLASS.
IT IS AN EXAMPLE OF SINGLETON CLASS.

Related Topics

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.