What is singleton class in Java and how can we make a class singleton?
A singleton class in Java is a class that restricts the instantiation of itself to just one object. In other words, it ensures that a class has only one instance and provides a global point to access that instance. This pattern is commonly used for logging, driver objects, caching, thread pools, database connections, and more.
To make a class singleton, you can follow these steps:
1. Private Constructor:
- Ensure that the class has a private constructor so that it cannot be instantiated from outside the class.
2. Static Instance Variable:
- Create a static instance variable of the class. This variable will hold the single instance of the class.
3. Static Method to Access Instance:
- Provide a static method (usually named
getInstance()) that returns the single instance of the class.
- Check if the instance is
null. If it is, create a new instance. If it’s not
null, return the existing instance.
With this setup, you ensure that there is only one instance of the class, and every time you call
getInstance(), you either create the instance (if it doesn’t exist) or return the existing instance.
The above implementation is not thread-safe. If multiple threads access the
getInstance() method simultaneously, it can create multiple instances of the singleton. To make it thread-safe, you can use synchronized blocks or utilize the Bill Pugh Singleton Design or Initialization-on-demand holder idiom (Static inner helper class), or use the
Enum type (since Java 5) to create a thread-safe singleton.
Example of Thread-Safe Singleton (Initialization-on-demand holder idiom):
In this approach, the
SingletonHelper class is loaded into memory only when it’s accessed, and it’s loaded in a thread-safe manner. This ensures that the singleton instance is created in a lazy and thread-safe manner.