LeetCampus
Interview Question

What is a singleton class in Java? And How to implement a singleton class?

July 24, 2025
0 views
Difficulty: Medium
Popularity: Common
Share on

Question Explanation

A singleton class in Java is a design pattern that restricts the instantiation of a class to a single instance. This is particularly useful when exactly one object is needed to coordinate actions across the system. Interviewers ask about singleton classes to assess a candidate’s understanding of design patterns, object-oriented programming principles, and the management of global states in applications. Singleton patterns are commonly used in scenarios such as logging, driver objects, caching, and thread pools. A common misconception is that a singleton is just a class with a private constructor, but it also involves ensuring that the instance is globally accessible and thread-safe. Implementing a singleton class can be straightforward, but it requires understanding how to manage instance creation and lifecycle effectively. This knowledge is crucial in real-world applications where resource management and performance are key. By testing this question, interviewers gauge a candidate's familiarity with best practices and their ability to apply design patterns in practical scenarios.

Sample Answers

Example 1: Basic Implementation of Singleton Class

To implement a singleton class in Java, you need to follow a few steps:

  1. Private Constructor: This prevents other classes from instantiating the singleton class directly.

    public class Singleton {
        private static Singleton instance;
        private Singleton() {} // Private constructor
    }
    
  2. Public Static Method: Create a public static method that returns the instance of the class. This method checks whether an instance already exists; if not, it creates one.

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    
  3. Thread Safety (Optional): If your application is multi-threaded, you might want to make the method synchronized to prevent multiple threads from creating separate instances.

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

This basic implementation ensures that only one instance of the Singleton class is created, thus fulfilling the singleton pattern's purpose.

Example 2: Thread-Safe Singleton with Bill Pugh Singleton Design

To enhance the basic singleton implementation for thread safety, you can use the Bill Pugh Singleton Design. This design leverages an inner static helper class to create the singleton instance. Here's how to do it:

  1. Inner Static Class: The inner class is only loaded when it's referenced, ensuring lazy initialization.

    public class Singleton {
        private Singleton() {} // Private constructor
    
        private static class SingletonHelper {
            private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton getInstance() {
            return SingletonHelper.INSTANCE;
        }
    }
    
  2. Advantages: This method is not only thread-safe but also prevents the overhead of synchronization with each method call. The instance is created only when the getInstance() method is called for the first time.

This approach is efficient and adheres to the lazy initialization principle, providing a clean and effective way to implement the singleton pattern.

Example 3: Enum Singleton Implementation

Another elegant way to implement a singleton class in Java is through the use of Enums. This method is inherently thread-safe and prevents multiple instances from being created. Here's how to implement it:

  1. Enum Declaration: Simply declare an enum with a single element.

    public enum Singleton {
        INSTANCE;
    }
    
  2. Usage: You can access the instance using Singleton.INSTANCE. This guarantees that no other instances can be created, as enums in Java are special and can only have a fixed set of constants.

    public class Main {
        public static void main(String[] args) {
            Singleton instance = Singleton.INSTANCE;
            // Use the instance as needed
        }
    }
    
  3. Benefits: Using enums for singleton implementation is considered the best practice in modern Java due to its simplicity and built-in serialization support, eliminating the need for additional code to handle serialization issues.

This method effectively combines simplicity with robustness, making it a preferred choice for implementing singletons.

Keywords

singletonJavadesign patternobject-oriented programmingsoftware engineering

Ready to practice more questions?

Explore our collection of technical interview questions from top companies.

View All Questions