0Pricing
Java Academy · Lesson

Singleton: Thread-Safe Implementations

Build a thread-safe Singleton using double-checked locking, enum, or holder pattern.

The Singleton Pattern

Singleton ensures that only one instance of a class exists in the JVM. Common use cases: configuration managers, connection pools, logging services.

Naive Singleton — Not Thread-Safe

The classic lazy singleton fails under concurrent access: two threads can both pass the null check simultaneously and create two instances.

public class Config {
    private static Config instance;
    private Config() {}
    public static Config getInstance() {
        if (instance == null) {              // race condition!
            instance = new Config();
        }
        return instance;
    }
}

All lessons in this course

  1. Singleton: Thread-Safe Implementations
  2. Factory Method Pattern
  3. Abstract Factory for Product Families
  4. Builder Pattern with Fluent API
← Back to Java Academy