Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

How to Create a Singleton Class in Java?

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

In Java, a Singleton class gives you the power to control object creation, allowing you to simultaneously create a single class object. This article will empower you with the knowledge of singleton classes in Java.

What is Singleton Class in Java?

In Java, a singleton class is a special class that allows only one instance or object of itself to be created. How often you try to create a new object from a singleton class does not matter. You’ll always get the same instance that was created initially. This is useful when exactly one object is needed to coordinate actions across the system. The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

How to Create a Singleton Class in Java?

Let’s see “how we can create a Singleton class in Java language”. A singleton class in Java ensures only one instance of itself exists. To create a singleton class with a private static instance variable and a private constructor. It provides a public static method to access the instance. This method checks if the instance exists.

 

Also Read: Classes and Objects in Java

Examples of Singleton Class in Java

Now, we will look at two singleton classes in Java examples:

 

Example 1:

 

The following program demonstrates the Singleton Class in Java using the Eager Initialisation.

 

Program

public class Singleton { //Create an instance of the class at the time of class loading private static final Singleton instance = new Singleton();  // private constructor to prevent instantiation private Singleton() {}  // method to return the single instance of the class public static Singleton getInstance() { return instance; } }

Example 2:

 

In this method, We will create the instance only when needed. This can save resources if our program does not use the instance immediately.

 

Program

public class Singleton { // declare the instance but don't create it yet private static Singleton instance;  // private constructor to prevent instantiation private Singleton() {}  // method to return the single instance of the class, creating it if necessary public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

Example 3: The Singleton class will use the getInstance() method in this example.

class Singleton_Example { public static void main(String args[]) {  Singleton x = Singleton.getInstance(); Singleton y = Singleton.getInstance(); Singleton z = Singleton.getInstance(); System.out.println("Hashcode of x is "+x.hashCode()); System.out.println("Hashcode of y is " + y.hashCode()); System.out.println("Hashcode of z is "+ z.hashCode());  if (x == y && y == z) { System.out.println("Three Object points same location in the memory"); } else { System.out.println( "Three Object is not point same location in the memory");  } } }  class Singleton { private static Singleton single_instance = null; public String s;  private Singleton(){ s = "This is a string class in Singleton"; }  public static synchronized Singleton getInstance(){ if (single_instance == null) single_instance = new Singleton();  return single_instance; } }

Output

Hashcode of x is 366712642 Hashcode of y is 366712642 Hashcode of z is 366712642 Three Object points same location in the memory
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Use Cases of Singleton Class in Java

There are many use cases of Singleton Class in Java. Let’s discuss the single-class use case.

 

  • Logging: A logging class where only one instance of the logger is required to log messages throughout the application.
  • Configuration Settings: A configuration class that reads settings from a file or environment and provides a single access point to these settings.
  • Connection Pooling: It manages a pool of database connections where a single instance controls access and manages the pool.
  • Caching: A cache manager stores frequently accessed data to improve performance, ensuring the single access point to the cache in Java.
  • Thread Pools: The Singleton class manages a threads pool for executing tasks where a single instance controls the pool.
  • Device Communication: The managing communication with hardware devices such as printers or scanners, ensuring only one instance of the communication handler.
  • File System Handling: A file system manager that provides a single access point to file operations, ensuring consistent file handling.

Benefits of Singleton Class in Java

Let’s discuss the benefits of Singleton Class in Java language:

 

  • Controlled Access to a Single Instance: The Singleton class ensures that only one instance of the class provides a controlled access point.
  • Reduced Memory Overhead: The Singleton class created only one instance; it reduces the application’s memory footprint.
  • Global Access: The Singleton class makes a global point of access to the instance, making it easy to access from anywhere in the application.
  • Lazy Initialisation: The singleton class can only create an instance when necessary to optimise resource usage.
  • Thread Safety: The Singleton class ensures thread-safe access to the instance.
  • Improved Maintainability: Singleton Class centralising the instance’s control makes the codebase easier to maintain and modify.

When to Use Singleton Class and When to Avoid It?

Java developers can use the singleton class when they require exactly one instance of a class throughout a program’s lifecycle. This is particularly helpful for managing resources such as database connections, logging systems, or configuration settings. The singleton class ensures these resources are easily accessible and consistent across the application.

Difference Between Singleton And Normal Class

This section will compare Singleton and Normal Classes in Java in tabular form.

 

Aspect Singleton Class Normal Class
Instance Creation Only one instance is created and shared across the application in the Singleton Class. Multiple instances can be created as needed.
Memory Usage Typically, it consumes less memory as only one instance exists. Memory usage depends on the number of instances created.
Use Case It is used when exactly one instance is needed to coordinate actions Used when multipole-independent instances are required.
Testing It can be harder to test due to the global state and single instances It is easier to test as instances can be created and destroyed independently.
Examples Logging, configuration settings, and connection pooling Models, Data Transfer objects, and utility classes.

Conclusion

In this article, we learned about the Singleton Pattern in Java language. It is a powerful tool to ensure that a class has only one instance and provides a global point of access to it. It can be particularly useful for classes that manage resources such as configuration settings, loggings and eager initialisation, lazy initialisation, thread-safe synchronisation, double-checked locking, or using a static inner help class. It can balance simplicity, performance, and thread safety based on the specific needs of your application. By understanding Java, developers can leverage the Singleton class easily and make the program more efficient.

FAQs
Yes, Java Developer can break the Singleton class using the Reflection technique. Reflection can be used to access the private constructor of the Singleton class and create multiple instances.
A Singleton class in Java ensures that only one instance of the class exists and provides a global access point to that instance.
Eager initialisation involves creating the Singleton class instance at class loading, ensuring that it is always available.
No, the singleton partner is not thread-safe by default.  You must implement thread-safe initialisation techniques like synchronised methods, double-checking locking, or the use of static inner classes to ensure thread safety when accessing the Singleton instance from the multiple threads in programming.
Yes, the Singleton class can be garbage collected if there are no active references to its instance, and it becomes eligible for garbage collection like any other object. However, This typically happens only in scenarios where the Singleton instance is no longer needed in Java.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved