×

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

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes 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.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.