Tip of the day #14

Learn the Singleton Pattern. If you are a Spring developer, by default, your beans are all singletons, so make sure you understand the pros and cons.

The Singleton Pattern

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it. It’s classified as a creational pattern because it lets you create an object while hiding the creation logic.

Basic implementation

You need to make sure that your class has only one instance, so you need to make the constructor private. You also need to create a static method that will be responsible for creating the instance if it doesn’t exist yet.

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

Tip: You can add a synchronized keyword to the getInstance() method, to make it thread-safe.

Spring - Singleton Beans

When you create a bean in Spring, by default, it will be a singleton. But it’s a singleton per Spring IoC container, so two different containers will have different instances of the same bean. The other difference from the Singleton Pattern is that Spring beans are created by the Spring IoC container, and not by the class itself.

Quarkus - ApplicationScoped Beans

Quarkus introduced the concept of ApplicationScoped beans, which uses client proxies to implement the singleton pattern. A client proxy is basically an object that delegates all method invocations to a target bean instance. See https://pt.quarkus.io/guides/cdi#client_proxies for more details. You can use @Singleton annotation, but @ApplicationScoped is the recommended approach.

How to

I will not create a repo for this. See https://refactoring.guru/design-patterns/singleton/java/example for a real example of today’s tip.

For Quarkus take a look in https://pt.quarkus.io/guides/cdi Spring https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html#beans-factory-scopes-singleton