Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java programming, the Singleton design pattern is a crucial concept for managing object creation. A Singleton class ensures that only one instance of the class is created throughout the lifecycle of an application. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system, such as in database connections, logging, or configuration management.
By enforcing a single instance, the Singleton pattern helps in controlling access to shared resources and ensures that the global state remains consistent.
To learn more about the classes and the Java, refer to the link.
In this article, we will discuss about the Singleton class in java, syntax, how to make a singleton class in java, and its implementation.
In Java, a Singleton class is one that enables access to it through a single instance at a time. This design approach limits unwanted class instantiation and ensures that only one class object exists at any specified instant per JVM instance. As a result of this design, any class specified as Singleton has a single instance with a global point of access to it. We cannot delete a singleton class at the end of the application's life cycle.
Purpose of Singleton Class
The Singleton class design pattern serves several key purposes in Java programming:
Controlled Access to a Single Instance: Ensures that only one instance of the class is created and provides a global point of access to that instance. This is crucial for managing shared resources like database connections or configuration settings.
Preventing Multiple Instances: Prevents the creation of multiple instances of a class, which can lead to inconsistent states and resource conflicts. It maintains a single, consistent object throughout the application's lifecycle.
Global Access Point: Provides a global access point to the single instance, allowing other parts of the application to use it without needing to pass it around. This simplifies code and ensures that the instance is accessible wherever it is needed.
Resource Management: Helps in managing system resources efficiently by controlling the creation of expensive-to-create objects, such as those that require significant initialization or configuration.
Lazy Initialization: Often implemented with lazy initialization, where the instance is created only when it is first requested, saving resources until the instance is actually needed.
Why do we need singleton class?
Restricting a class's instance generation saves memory space because the object is no longer produced when a new request is made. That's why the Singleton pattern in Java is most commonly found in multi-threaded and database applications. It is mostly used for logging, caching, thread pooling, configuration settings, and other purposes.
How to Creat a singleton class in java?
Here are the steps to create a Singleton class in Java:
Declare a Private Static Instance: Define a private static variable to hold the single instance of the class. This ensures that the instance is only accessible within the class.
Make the Constructor Private: Create a private constructor to prevent direct instantiation of the class from outside. This ensures that the class can only be instantiated within its own code.
Provide a Public Static Method for Access: Implement a public static method that returns the single instance of the class. This method uses lazy initialization to create the instance only when it is needed.
Ensure Thread Safety (Optional): For a thread-safe implementation, use synchronized blocks or other concurrency mechanisms to handle multiple threads accessing the instance simultaneously.
Double-Check Locking (Optional): For improved performance in a multithreaded environment, use double-checked locking to reduce the overhead of synchronization.
Implement Serialization (Optional): To maintain the singleton property during serialization, implement the readResolve method.
To make a singleton class, we require mainly three things:
A static member of the class
Private constructor
A static factory method
Syntax
// java syntax to show how to make singleton class in java
class codingninjas {
// private field that refers to the object
private static ninjas object;
private ninjas() {
// constructor of the codingninjas class
}
public static ninjas getInstance() {
// write code that allows you to create only one object
// access the object as per the need
}
}
Implementation 1
Java
Java
// java program to show how to make singleton class in java. class singleton { private static singleton singletonObject;
private singleton() { }
public static singleton getInstance() { singletonObject = new singleton(); return singletonObject; }
public void getConnection() { System.out.println("Congratulations! you have learned how to make singleton class in java."); } }
class codingninjas { public static void main(String[] args) { singleton obj;
// refers to the only object of Database obj = singleton.getInstance(); obj.getConnection(); } }
You can also try this code with Online Java Compiler
Congratulations! you have learned how to make singleton class in java (without if condition).
Explanation
When we execute the getInstance() function for the first time in a singleton class, it generates the object of the class with a name single instance and returns it to variable. Because a single instance is a static variable, it is set to some object rather than null. If we attempt to call the getInstance() function again, since the single instance is not null in the example, it is returned to a variable rather than instantiating the Singleton class again. We can handle it by the if condition. We will discuss this in a further example.
// java program on how to make singleton class in java class singleton { private static singleton singletonObject = null;
private singleton() { }
public static singleton getInstance() { // create object if it's not already created if (singletonObject == null) { singletonObject = new singleton(); }
// returns the singleton object return singletonObject; }
public void getConnection() { System.out .println("Congratulations! you have learned how to make singleton class in java (with if condition)."); } }
class codingninjas { public static void main(String[] args) { singleton obj;
// refers to the only object of Database obj = singleton.getInstance(); obj.getConnection(); } }
You can also try this code with Online Java Compiler
Congratulations! you have learned how to make singleton class in java (with if condition).
Explanation
When we first execute the Singleton() function in the singleton class, it generates an object of class Singleton with the name singleobject and returns it to the variable. Because a singleobject is static here, it is changed from null to some object. If we try to call the Singleton() function again, it is returned to a variable instead of instantiating the Singleton class again.
Difference between Normal Class and Singleton Class
Parameters
Normal Class
Singleton Class
Instance Creation
Multiple instances can be created using the new keyword.
Only one instance is created and used throughout the application.
Access
Instances can be accessed by creating new objects.
The single instance is accessed through a static method.
Global Access Point
No built-in global access point.
Provides a global access point through a static method.
Resource Management
Multiple instances can lead to resource duplication and potential conflicts.
Ensures centralized resource management with a single instance.
Constructor Visibility
Constructors are typically public, allowing multiple instantiations.
Constructor is private, preventing direct instantiation.
Thread Safety
Not inherently thread-safe; requires additional measures for concurrency.
Often includes mechanisms for thread safety, such as synchronization.
Initialization
Can be initialized multiple times.
Initialized only once, typically using lazy initialization.
Usage
Suitable for scenarios where multiple instances are needed.
Ideal for scenarios requiring a single instance for consistency and control.
Frequently Asked Questions
Why should we use singleton class?
Singleton classes ensure controlled access to a single instance, reduce memory overhead, maintain consistent state, enable lazy initialization, simplify global access, and improve testing and maintainability in applications.
How many ways can you write a singleton class in Java?
There are several ways to implement a singleton class in Java, including the eager initialization, lazy initialization (thread-safe), double-checked locking, and using an enum. Each method has its own advantages and trade-offs regarding performance and thread safety.
Can we inherit a singleton class in Java?
In Java, a singleton class cannot be inherited in a meaningful way, as the singleton pattern restricts instantiation to a single instance. If a subclass is created, it may lead to multiple instances, violating the singleton property. However, a subclass can be created, but it's typically discouraged.
Can we say that the singleton class is thread-safe?
A singleton class is not thread-safe. Numerous threads can access the singleton simultaneously and generate multiple objects, which violates the concept of a singleton.
Conclusion
The Singleton class design pattern is a fundamental concept in Java that ensures a class has only one instance throughout the application's lifecycle, providing a global point of access to that instance. By enforcing a single instance, the Singleton pattern helps manage shared resources efficiently, maintain global state consistency, and control access to critical resources.