How to Create a Singleton with Java Enums

A job interview coming? And you don’t remember the Singleton design pattern?

Do you need to implement the Singleton Design pattern, but today you want to do it right, thread-safe, and in a cool-way with enums?

Every Java developer needs to implement the Singleton pattern one day or another. So, let’s do it today.

The Singleton Design Pattern

The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. Think of it as the designated driver of your application—there’s only one, and everyone relies on it.

Singleton Design Pattern

The idea is simple: if you’ve got something that should only exist in one place (like a database connection pool or a logging service), the Singleton is the needed pattern.

Old Way

Let’s now see how to implement the Singleton in the old way.

class MySingleton {
    private static MySingleton INSTANCE;

    private MySingleton() {
        super();
    }

    private static MySingleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MySingleton();
        }
        return INSTANCE;
    }

    // other methods
    public void doSomething() {
        // do... something
    }
}

class MySecondClass {
    public static void main(String[] args) {
        MySingleton.getInstance().doSomething();
    }
}

What key elements need a Singleton class?

  • A private constructor. This way, I ensure only the Class itself can create an instance of the Class.
  • The instance must be saved in the static field. This way, the memory place to access the Class is always the same, I’m sure I’m using always the same instance.
  • A static access method. To ensure I’m using always the same instance, and which calls the private constructor if the instances wasn’t initialized yet.

But as the title says, this is the old way. What are the disadvantages of this implementation?

What if two methods call the access method (and implicitly the constructor method) at the same time? I mean, at the exact same time!

Two instances will be created, but only one will be saved. And this will occur if I have an application with a high load.

With Enums

“Ok, the first solution won’t be perfect, but it does the job 90% of the time.”

But that’s not how a Singleton should work, and I have a better and simpler way to implement it.

public enum MySingleton {
    INSTANCE;

    // other methods
    public void doSomething() {
        // do... something
    }
}

class MySecondClass {
    public static void main(String[] args) {
        MySingleton.INSTANCE.doSomething();
    }
}

By definition, an enum is already a Singleton: it has a private constructor, the value is saved in a static field, and I have a static access method.

Don’t tell me the implementation is harder this way? And the enum are thread-safe. I don’t need to worry about multi-threading access.

Conclusion

The Singleton pattern is a pattern that I use… not everyday, but I do use it in some cases.

It’s a pattern asked in interviews. That’s for sure.

But overusing it isn’t a best practice. It’s hard to test. Testing static method is always hard to mock. So, don’t overuse it.


Never Miss Another Tech Innovation

Concrete insights and actionable resources delivered straight to your inbox to boost your developer career.

My New ebook, Best Practices To Create A Backend With Spring Boot 3, is available now.

Best practices to create a backend with Spring Boot 3

Leave a comment

Discover more from The Dev World - Sergio Lema

Subscribe now to keep reading and get access to the full archive.

Continue reading