DEV Community

Cover image for Don’t Let Your Singleton Break! Here’s How to Make It 100% Thread-Safe in Java
Aman
Aman

Posted on

Don’t Let Your Singleton Break! Here’s How to Make It 100% Thread-Safe in Java

In this post, we’ll explore several ways to implement a thread-safe singleton in Java, including eager initialization, double-checked locking, and the inner static class approach. We’ll also discuss why the final keyword is beneficial in ensuring the integrity of a singleton.

Why Use a Singleton?

Singletons are useful when you need exactly one instance of a class throughout the application. Common use cases include managing shared resources such as logging, configuration, or connection pools. A singleton ensures that multiple requests to access a class share the same instance, rather than creating new ones.

1. Eager Initialization: The Simplest Singleton

The eager initialization pattern creates the singleton instance when the class is loaded. This is straightforward and ensures thread safety because the instance is created when the class is loaded by the JVM.

public final class Singleton {
    // Instance is created at class loading time
    private static final Singleton INSTANCE = new Singleton();

    // Private constructor prevents instantiation from other classes
    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}
Enter fullscreen mode Exit fullscreen mode

Pros and Cons of Eager Initialization

Pros:

  • Simple and thread-safe by default, as the JVM guarantees class initialization is thread-safe.
  • No need for synchronization or additional complexity.

Cons:

  • Instance is created whether it’s used or not, which can lead to wasted resources if the singleton is never needed.

When to Use It: Eager initialization is best when the singleton class is lightweight and you’re certain it will be used during the application’s runtime.


2. Lazy Initialization with Double-Checked Locking

In cases where you want to delay the creation of the singleton until it’s needed (known as lazy initialization), double-checked locking provides a thread-safe solution. It uses minimal synchronization and ensures the instance is created only when it’s accessed for the first time.

public final class Singleton {  // Marked as final to prevent subclassing

    // volatile ensures visibility and prevents instruction reordering
    private static volatile Singleton instance;

    // Private constructor prevents instantiation from other classes
    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {               // First check (no locking)
            synchronized (Singleton.class) {   // Locking
                if (instance == null) {        // Second check (with locking)
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

Why Double-Checked Locking Works

  1. First Check: The if (instance == null) check outside the synchronized block allows us to avoid locking every time getInstance() is called. This improves performance by bypassing the synchronized block for future calls after initialization.

  2. Synchronized Block: Once instance is null, entering the synchronized block ensures only one thread creates the Singleton instance. Other threads that reach this point must wait, preventing race conditions.

  3. Second Check: Inside the synchronized block, we check instance again to ensure no other thread has initialized it while the current thread was waiting. This double-check ensures only one Singleton instance is created.

Why volatile is Needed

The volatile keyword is essential in the double-checked locking pattern to prevent instruction reordering. Without it, the statement instance = new Singleton(); might appear completed to other threads before it’s fully initialized, leading to a partially constructed instance being returned. volatile guarantees that once instance is non-null, it’s fully constructed and visible to all threads.

Why final is Good Practice

The final keyword is used here to prevent subclassing. Marking the Singleton class as final has two primary benefits:

  1. Prevents Subclassing: By making the class final, we prevent other classes from extending it. This ensures that only one instance of the Singleton class can exist since subclassing could lead to additional instances, which would break the singleton pattern.

  2. Signals Immutability: final serves as a clear indicator to other developers that the singleton class is intended to be immutable and should not be extended. This makes the code easier to understand and maintain.

In short, final reinforces the singleton’s integrity and helps avoid unexpected behavior from subclassing.

Pros and Cons of Double-Checked Locking

Pros:

  • Lazy initialization saves resources by delaying creation until needed.
  • Minimal synchronization overhead due to double-checking.

Cons:

  • Slightly more complex and requires volatile for safety.
  • Can be overkill for simpler singleton needs where eager initialization is sufficient.

When to Use It: This pattern is useful when the singleton class is resource-intensive and might not always be needed, or when performance in a multithreaded environment is a concern.


3. Inner Static Class: A Cleaner Lazy Initialization Alternative

An alternative thread-safe approach to lazy initialization is the inner static class pattern. This leverages Java’s class-loading mechanism to initialize the singleton instance only when it’s needed, without explicit synchronization.

public final class Singleton {
    private Singleton() {}

    // Inner static class responsible for holding the Singleton instance
    private static class SingletonHelper {
        private static final Singleton INSTANCE = new Singleton();
    }

    // Public method to provide access to the instance
    public static Singleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}
Enter fullscreen mode Exit fullscreen mode

How the Inner Static Class Works

In this pattern, the SingletonHelper class is only loaded when getInstance() is called for the first time. This triggers the initialization of INSTANCE, ensuring lazy loading without requiring synchronized blocks.

Pros and Cons of Inner Static Class

Pros:

  • Thread-safe without the need for volatile or synchronized blocks.
  • Simple and clean, with lazy initialization by design.

Cons:

  • Slightly less intuitive for new developers unfamiliar with Java’s class-loading mechanics.

When to Use It: Use the inner static class pattern when you want lazy initialization with clean, maintainable code. This is often the preferred choice due to simplicity and thread-safety.


Wrapping Up

We’ve looked at three popular ways to implement a thread-safe singleton in Java:

  1. Eager Initialization: Best for simple cases where the singleton is lightweight and will always be used.
  2. Double-Checked Locking: Great for performance-sensitive, multithreaded environments with a need for lazy initialization.
  3. Inner Static Class: A clean and thread-safe approach to lazy initialization using Java’s class-loading behavior.

Each approach has its strengths and is suited for different scenarios. Try them out in your own projects and see which one works best for you! Let me know in the comments if you have a preferred approach or any questions.

Happy coding! 👨‍💻👩‍💻

Top comments (0)