Java Design Singleton — Free Java Tutorial

Learn Java Design Singleton in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Java Design Singleton — Free Java Tutorial

Learn Java Design Singleton in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

TL;DR: Learn Java Design Singleton in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

Java Design Singleton in Java

The Singleton pattern ensures a class has only one instance and provides a global access point to it. Used for: configuration, logging, thread pools, database connections.

Classic lazy-initialization: the instance is created only when first needed. Thread-safe version uses double-checked locking with volatile.

The enum singleton (Josh Bloch's recommendation) is the safest and simplest: it handles serialization and reflection attacks automatically.

Overuse of Singleton is an anti-pattern — it creates hidden global state and makes testing harder. Prefer dependency injection when possible.

Java Design Singleton — Syntax

// Thread-safe lazy singleton
public class Config {
    private static volatile Config instance;
    private Config() {}  // private constructor

    public static Config getInstance() {
        if (instance == null) {
            synchronized (Config.class) {
                if (instance == null)
                    instance = new Config();
            }
        }
        return instance;
    }
}

// Enum singleton (best approach)
enum AppConfig { INSTANCE;
    public String get(String key) { ... }
}

Learn Java Design Singleton step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →