Design Patterns In Java: Singleton

Suganya Nesappan
4 min readFeb 15, 2024

--

The primary purpose of a Java Singleton class is to restrict the limit of the number of object creations to only one. This often ensures that there is access control to resources, for example, socket or database connection.

Memory space wastage does not occur with the use of the singleton class because it restricts instance creation. The object creation will take place only once instead of creating it each time a new request is made.

Using design patterns we can develop programs that are more efficient, flexible, maintainable, and reusable.

How to implement the Singleton Pattern in a Program?

We create a singleton class and have its constructor as “private” so that the class cannot be instantiated. Then we create a private instance of this singleton class inside the class itself. Then we have a special public method getInstance() that returns a singleton object.

Example 1: Eager initialization

Output:

Note: If we try to create an object of the singleton class using a new operator, the compiler will give a compilation error. We obtain the object of the singleton class using the getInstance() method and then we can use it as usual to access methods.

Example 2: Static block initialization

Static block initialization implementation is similar to eager initialization, except that an instance of the class is created in the static block that provides the option for exception handling.

public class StaticBlockSingleton {

private static StaticBlockSingleton instance;

private StaticBlockSingleton(){}

// static block initialization for exception handling
static {
try {
instance = new StaticBlockSingleton();
} catch (Exception e) {
throw new RuntimeException("Exception occurred in creating singleton instance");
}
}

public static StaticBlockSingleton getInstance() {
return instance;
}
}

Example 3: Lazy Initialization

A lazy initialization method to implement the singleton pattern creates the instance in the global access method. Here is the sample code for creating the singleton class with this approach:

public class LazyInitializedSingleton {

private static LazyInitializedSingleton instance;

private LazyInitializedSingleton(){}

public static LazyInitializedSingleton getInstance() {
if (instance == null) {
instance = new LazyInitializedSingleton();
}
return instance;
}
}

This implementation works fine in the case of the single-threaded environment, but when it comes to multi-threaded systems, it can cause issues if multiple threads are inside the if condition at the same time.

Example 4: thread-safe singleton

A simple way to create a thread-safe singleton class is to make the global access method synchronized so that only one thread can execute this method at a time. Here is a general implementation of this approach:

package com.journaldev.singleton;

public class ThreadSafeSingleton {

private static ThreadSafeSingleton instance;

private ThreadSafeSingleton(){}

public static synchronized ThreadSafeSingleton getInstance() {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
return instance;
}

}

Advantages

  • As only one instance of the singleton class is used, we save memory.
  • Also, ensures reusability as the same singleton object is used again and again.

When To Use Singleton Class And When To Avoid It?

Using a singleton class in Java is suitable when you require exactly one instance of a class throughout your program’s lifecycle. This is particularly helpful for managing resources such as database connections, logging systems, or configuration settings. Singleton ensures that these resources are easily accessible and consistent across the application.

However, it’s important to avoid using singletons when they’re unnecessary or could hinder your code’s flexibility. Avoid them if they lead to a global state that’s difficult to manage or if they complicate unit testing due to tightly coupled dependencies.

Frequently Asked Questions

Why would you use a singleton class?

The Singleton’s purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

What is the difference between singleton class and normal class?

For a normal class, we need to create an object first to use its properties and methods. For static classes, we do not need to instantiate and we access properties and methods by class name. For singleton classes, we create an instance using its static property and at any time it creates a single instance of a class.

Conclusion

Singleton pattern is the simplest design pattern and the factory method is supposed to be a common design pattern that is widely used

--

--