Singleton Class in Java: Everything You Need to Know

Java programming is a wide world. There are many classes and objects. They collaborate to bring applications to life. In this, a unique concept called the  Singleton Class is known for its simplicity and power. Singleton class offers a magical blueprint that ensures only one instance of a class throughout the lifetime of an application. There are many essential uses of the Singleton class in Java.

This blog will explain the Singleton Class in a most straightforward way. This will be useful for beginners as well as advanced who are pros in coding. By the end of this guide, you'll understand how to make a Singleton class in Java and appreciate its elegance in solving real-world programming challenges.

What Is Singleton Class In Java?

A singleton class in Java is a special class that allows only one instance (or object) of itself to be created. Imagine it like a unique key that opens a special door. No matter how many times you try to create a new object from a singleton class, you'll always get the same instance that was created initially.

Think of it like having only one unique cookie jar. Even if you open the jar multiple times, you'll always get cookies from the same jar. In Java, a singleton class ensures that you have only one "jar" (object) for that class throughout your program.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

How To Create A Singleton Class In Java?

Now that you know the introduction, let's discuss how to create a singleton class in Java. A singleton class in Java ensures only one instance of itself exists. To make one, create a class with a private static instance variable and a private constructor. Then, provide a public static method to access the instance. This method checks if the instance exists; if not, it creates one. You'll always get the same instance wherever you call the method. This is how you can create a singleton class in Java. Remember, singletons help control access to shared resources and maintain consistency across the program.

Examples of Singleton Class in Java

Now, we will look at two singleton classes in Java examples

Example 1: Eager Initialization

public class EagerSingleton {

    private static final EagerSingleton instance = new EagerSingleton();

    private EagerSingleton() {

        // Private constructor to prevent external instantiation

    }

    public static EagerSingleton getInstance() {

        return instance;

    }

}

Example 2: Lazy Initialization

public class LazySingleton {

    private static LazySingleton instance;

    private LazySingleton() {

        // Private constructor to prevent external instantiation

    }

    public static LazySingleton getInstance() {

        if (instance == null) {

            instance = new LazySingleton();

        }

        return instance;

    }

}

In the first example (Eager Initialization), the instance is created as soon as the class is loaded, ensuring that the instance is always available when needed.

In the second example (Lazy Initialization), the instance is created only when the getInstance() method is called for the first time. This can save resources if the instance is not always needed. However, it's important to note that this approach isn't thread-safe and might lead to issues in a multithreaded environment.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Use Cases and Benefits of Singleton Class in Java

Singleton classes in Java are useful when you need only one class instance to control shared resources or ensure consistent behavior. They manage database connections, configuration settings, and thread pools. Singleton can simplify access, reduce memory consumption, and maintain data integrity if you want a global point of control in your program. It prevents multiple instances that could cause conflicts. 

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. 

Difference Between Singleton And Normal Class

Singleton Class 

A singleton class is designed to have only one instance throughout the program's execution. Singleton classes control access to their single instance, preventing the unnecessary creation of multiple instances. We hope that you know how to make a class singleton in Java.

Normal Class

A normal class can have multiple instances created whenever needed. Each instance operates independently, and you can create as many objects of that class as you want. Normal classes are used when you need to work with various instances that don't need to be globally controlled or shared. Normal classes allow any independent instances to be created. 

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Conclusion

Hope this article was able to give you a better understanding of the Singleton class in Java. If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn’s Professional Certificate Program in Full Stack Web Development - MERN. This course, in collaboration with IIT Madras, can help you hone the right development skills and make you job-ready. 

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

FAQs

1. How is thread safety achieved in a Singleton class?

There are many ways to achieve thread safety in Singleton Class. It includes eager Initialization, Synchronized Method, Double Checked Locking, Initialization-on-demand Holder Idiom, Using the 'volatile' keyword and Enum Singleton.

2. Can a Singleton class be subclassed?

Yes, it is possible. But it can lead to many complications. Each Subclass would have its instance. It will break the intended single-instance behavior. The Subclass should handle initialization and constructor access differently, potentially affecting the singleton pattern's purpose. 

3. How does serialization affect Singleton?

Serialization can affect the behavior of Singleton classes in Java. When a Singleton class is serialized and then deserialized, it can create multiple instances, violating the Singleton pattern's goal of having only one instance. 

4. Is the Singleton pattern suitable for all scenarios?

No, the Singleton pattern is not suitable for all scenarios. It is useful to manage global resources and ensure a single instance. It might not be suitable where flexibility and multiple instances are needed. 

5. Can I use Enum for implementing Singleton?

You can use an Enum to implement the singleton pattern in Java. Enum values are inherently single instances by design, making them a straightforward and thread-safe way to create Singleton objects. 

Here's an example of how you can achieve this:

public enum SingletonEnum {

    INSTANCE;  // The single instance of the SingletonEnum class

    

    // Add your methods and instance variables here

    

    public void doSomething() {

        // Your code here

    }

}

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.