You are currently viewing Singleton Class in Java with Implementation and Example

Singleton Class in Java with Implementation and Example

In this tutorial, you will learn about Singleton Class in Java with an example in detail.

  • So far, we’ve learned and implemented standard Java classes. Now we’ll look at the Singleton class in Java. A Singleton class in Java is one of the five Java creational singleton design patterns.
  • These classes are distinct from regular classes, and we use them to meet specific needs, simplify usage, and eliminate bottlenecks encountered during java application development.
  • In this article, we will define a singleton class and see how to implement one in Java. This class can be implemented in a variety of ways in Java. We will go over each of these methods in detail, including implementation and examples.
Note: Singleton is a design pattern in Java that ensures a class can only have one object.

A singleton class in object-oriented programming is a class that can only have one object (an instance of the class) at a time.

If we try to instantiate the Singleton class after the first time, the new variable also points to the first instance created. So, any changes we make to any variable within the class via any instance affect the variable of the single instance created and are visible if we access that variable via any variable of that class type defined.

A class must implement the following properties in order to be a singleton class:

  • Create a private constructor for the class to limit the creation of objects outside of the class.
  • Create a private class type attribute that refers to a single object.
  • Make a public static method that allows us to create and access the object we just made. We’ll add a condition to the method that prevents us from creating more than one object.

The singleton design pattern comes in two patterns.

  • Early Instantiation: the creation of an instance at the time of load.
  • Lazy instantiation: the creation of instances only when they are needed.

Example: Java Singleton Class Syntax

class SingletonExample {

   // private field that refers to the object
   private static SingletonExample singleObject;
                                              
   private SingletonExample() {
      // constructor of the SingletonExample class
   }

   public static SingletonExample getInstance() {
      // write code that allows us to create only one object and access it as needed
   }
}

Here,

  • static private SingletonExample singleObject – a reference to the class’s object.
  • private SingletonExample() – a private constructor that prevents objects from being created outside of the class from being created.
  • static public SingletonExample getInstance() – this method returns a reference to the class’s sole object. Because the method is static, the class name can be used to access it.

How to Use Singleton Class in Java?

Singleton’s function is to control object creation by limiting the number of objects to one. Because there is only one Singleton instance, any instance fields of a Singleton, like static fields, will appear only once per class. Access to resources, such as database connections or sockets, is frequently controlled by singletons.

For example, if you have a license for only one database connection or if your JDBC driver has issues with multithreading, the Singleton ensures that only one connection is made or that only one thread can access the connection at a time.

  • When working with databases, singletons can be used. They can be used to create a connection pool in order to access the database while using the same connection for all clients.

as an example:

class Database {
   private static Database Object;

   private Database() {      
   }

   public static Database getInstance() {

      // create object if it's not already created
      if(Object == null) {
         Object = new Database();
      }

       // returns the singleton object
       return Object;
   }

   public void getConnection() {
       System.out.println("You are link with the database");
   }
}

class Main {
   public static void main(String[] args) {
      Database db;

      // refers to the only object of Database
      db= Database.getInstance();
      
      db.getConnection();
   }
}

When we run the program, we will get the following results:

You are link with the database

In the preceding example:

  • Database is a singleton class that we have created.
  • The Object is a field of the class type. This will refer to the class Database object.
  • Database() is a private constructor that prevents objects from being created outside of the class.
  • The static class type method getInstance() exposes the class’s instance to the outside world.
  • We have a class type variable db in the Main class. We use db to call getInstance() to get the Database only object.
  • The method getConnection() can only be accessed through the Database object.
  • Because the Database can only contain one object, all clients can access the database using a single connection.

Example 2: The following implementation demonstrates a classSingleton design pattern.

public class ClassSingleton {

   private static ClassSingleton instance = null;
   private ClassSingleton() {
      // Exists only to defeat instantiation.
   }

   public static ClassSingleton getInstance() {
      if(instance == null) {
         instance = new ClassSingleton();
      }
      return instance;
   }
}
  • The static getInstance() method returns a static reference to the lone singleton instance maintained by the ClassSingleton class.
  • To create the singleton, the ClassSingleton class uses a technique known as lazy instantiation;, as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are only created when they are required.

What is the difference between the Normal and Singleton classes?

A Singleton class differs from other classes in terms of the process of instantiating the class’s object. A java constructor is used to instantiate a normal class. To instantiate a singleton class, on the other hand, we use the getInstance() method.

Another distinction is that a normal class is destroyed at the end of an application’s lifecycle, whereas a singleton class is not destroyed at the end of an application’s lifecycle.

Singleton Class Implementation

A Singleton class can be implemented or designed in a variety of ways. The following are some popular methods for creating a Singleton class:

  1. Eager Initialization Method
  2. Lazy Initialization Method
  3. Thread Safe Singleton Method
  4. Lazy Initialization with Double Lock Method
  5. Lazy Load Method

Eager Initialization Method

The Eager Initialization method is the most fundamental and straightforward method for creating a Singleton class. When the JVM loads memory to the object, the object or instance of the class is created. We accomplish this by assigning the reference directly to the object.

When we know that the program will always use the object/instance of this class, we can use this technique. In addition, we use this technique when the cost of creating the instance is not prohibitively expensive in terms of resources and time.

To create a singleton class using the Eager Initialization method, follow the steps below:

  • Declare the class constructor as private.
  • Now, for this Singleton class, create a private class member.
  • The next step is to define a factory method that returns the Singleton class’s object.
public class EagerInitialization
{
  //Instance will be created at load time
  private static EagerInitialization object = new EarlyInitialization();
  public String string;

  //Creating private constructor
  private EagerInitialization()
  {
    string = "Welcome to Developers Dome Tutorial of Java";
  }

  //Declaring static method
  public static EagerInitialization getInstance()
  {
    return object;
  }

  public static void main(String args[])
  {
    EagerInitialization e = EagerInitialization.getInstance();
    //original string
    System.out.println("Developers Dome:");
    System.out.println(e.string);

    //text in upper case
    System.out.println("String:");
    e.string = (e.string).toUpperCase();
    System.out.println(e.string);
  }
}

Output:

Developers Dome:
Welcome to Developers Dome Tutorial of Java
String :
WELCOME TO DEVELOPERS DOME TUTORIAL OF JAVA

You can see in the code above that instead of invoking the class constructor, we must use the getInstance() method each time we instantiate an object.

Pros and Cons of Eager Initialization Method

ProsCons
Eager Initialization is a very simple technique to implement.Because a class’s object is always created whether you need it or not, this may result in resource waste.
In addition, the unnecessary creation of an instance wastes CPU time.
We cannot use Exception Handling with this approach.

Lazy Initialization Method

As we know, using the Eager Initialization method to create a singleton class may result in the creation of an object that is not required by the application. To address this issue, another technique for creating a singleton class is the Lazy Initialization method.

The Lazy Initialization method postpones class instantiation until it is required. In other words, the object is only created if it is needed. This method aids in avoiding the creation of unnecessary class instances.

To create a singleton class using the Lazy Initialization method, follow the steps below:

  • Declare the class constructor as private.
  • Make a private static instance of this class without initializing it.
  • Create a factory method as the final step. This method will first determine whether or not the instance member is null. If it is not null, it will create an instance of the singleton class for you and return it; otherwise, no instance will be created.
public class LazyInitialization
{
  // private instance, so that it can be
  // accessed by only by getInstance() method
  private static LazyInitialization instance;
  public String string;
  private LazyInitialization ()
  {
    // private constructor
    string = "Welcome to Developers Dome Tutorial of Java";
  }
  //method to return instance of class
  public static LazyInitialization getInstance()
  {
    if (instance == null)
    {
      // if instance is null, initialize
      instance = new LazyInitialization ();
    }
    return instance;
  }
  public static void main(String args[])
  {
    LazyInitialization l = LazyInitialization .getInstance();
    //original string
    System.out.println("The String is:");
    System.out.println(l.string);
  }
}

Output:

The String is:
Welcome to Developers Dome Tutorial of Java

Pros and Cons of Lazy Initialization Method

ProsCons
The creation of an object occurs only when it is needed. This avoids wasting resources and CPU time.
This technique also allows for exception handling.
Each time, the condition of null must be checked.
We cannot directly access the class’s object.

Thread Safe Singleton Method

Even in a multithreaded environment, a thread-safe singleton method creates a Singleton class. The getInstance() method must be marked as synchronized.’ Marking this method as synchronized prevents multiple threads from accessing it at the same time.

public class ThreadSafeSingleton
{
  //Thread Safe Singleton

  private static ThreadSafeSingleton instance;
  private ThreadSafeSingleton()
  {
    // private constructor
  }
  //Making the getInstance method as synchronized
  public static synchronized ThreadSafeSingleton getInstance()
  {
    if(instance == null)
    {
      instance = new ThreadSafeSingleton();
    }
    return instance;
  }
}

Pros and Cons of Thread Safe Singleton Method

ProsCons
The Thread-safe method allows for lazy initialization.
It also has thread safety.
The getInstance() method is synchronized, which slows down application performance by limiting the number of threads that can be accessed at the same time.

singleton class in java , how to create singleton class in java, singleton class in java example, create singleton class in java, thread-safe singleton class in java, how to make singleton class in java, use of singleton class in java, how to make a class singleton in java, create a singleton class in java, singleton class in java, how to create singleton class in java, singleton class in java example, create singleton class in java, thread-safe singleton class in java, how to make singleton class in java, use of singleton class in java, how to make a class singleton in java, create a singleton class in java, singleton class in java, how to create singleton class in java, singleton class in java example, create singleton class in java, thread-safe singleton class in java, how to make singleton class in java, use of singleton class in java, how to make

Lazy Initialization with Double Lock Method

We solve the overhead problem of synchronized methods with this approach. The getInstance() method is not synchronized in this case. Rather than synchronizing it, we enclose the code for creating objects within a synchronized block.

By doing so, only a small number of threads must wait, and only for the first time. This method usually improves the application’s performance.

public class LazyDoubleLock
{
        // Java code to demonstrate double-check locking a private instance so that it can only be accessed via the getInstance() method.
        private static LazyDoubleLock instance;
        public String string;

        private LazyDoubleLock()
        {
                // private constructor
                string = "Welcome to Developers Dome Java Tutorial";
        }
        public static LazyDoubleLock getInstance()
        {
                if (instance == null)
                {
                        //synchronized block to remove overhead
                        synchronized (LazyDoubleLock.class)
                        {
                                if(instance==null)
                                {
                                        // if instance is null, initialize
                                        instance = new LazyDoubleLock();
                                }
                        }
                }
                return instance;
        }
        public static void main(String args[ ])
        {
                LazyDoubleLock ld = LazyDoubleLock.getInstance();
                //original string
                System.out.println("Developers Dome:");
                System.out.println(ld.string);

                //text in upper case
                System.out.println("String:");
                ld.string = (ld.string).toUpperCase();
                System.out.println(ld.string);

        }
}

Output:

Developers Dome:
Welcome to Developers Dome Tutorial of Java
String :
WELCOME TO DEVELOPERS DOME TUTORIAL OF JAVA

Pros and Cons of Lazy Initialization with Double Lock Method

ProsCons
Lazy initialization is an option.
It is also a method that is thread-safe.
Because of the synchronized block, performance improves.
It may have an impact on the performance of the first time.

Lazy Load Method

The JVM uses the Lazy Load method to load static data members only when they are needed. As a result, no object is created when the JVM loads the singleton class into the JVM.

public class LazyLoadMethod
{
  //Lazy Load Method
  private LazyLoadMethod()
  {

  }
  private static class SingletonClassHolder
  {
    private static LazyLoadMethod instance= new LazyLoadMethod();
  }
  public static LazyLoadMethod getInstance()
  {
    return SingletonClassHolder.instance;
  }
}

More About Singleton Class

  • The primary goal of the Single class is to limit the number of objects that can be created to one. This frequently ensures that resources, such as a socket or database connection, have access control.
  • Because it restricts instance creation, the use of a singleton class does not result in memory space waste. Because the object will be created only once rather than each time a new request is made.
  • This single object can be used repeatedly based on the requirements. This is why multi-threaded and database applications frequently use the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and other purposes.

You may like:

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Hope this article will guide you to recognize all about Singleton Class in Java with Implementation and Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has 4 Comments

Leave a Reply