Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Singleton

Синглтон

This design pattern limits a class to one instance within a defined scope and provides a common way to get that instance. Each caller gets the same object, not a new copy.

Also known as: одиночка

What it means

Imagine several modules reporting metrics. If each creates its own registry, the application may end up with separate sets of counters. Sharing a registry puts those counters in one place. The Singleton pattern goes further than simply sharing an object: it controls how the object is created and gives callers a common way to retrieve it.

“One” always needs a scope. If two servers run the same application, each can have its own Singleton. The pattern neither shares memory between servers nor elects one server to do a job.

How it works

A classic implementation hides the constructor and exposes a class-level accessor such as getInstance(). The class creates its instance either as part of class initialization or on the first request. Creating it on demand is called lazy initialization. It avoids work if no caller needs the object, but it must also handle two callers arriving at the same time.

A Java example

public final class MetricsRegistry {
    private MetricsRegistry() {}

    private static class Holder {
        private static final MetricsRegistry INSTANCE = new MetricsRegistry();
    }

    public static MetricsRegistry getInstance() {
        return Holder.INSTANCE;
    }
}

Calling getInstance() for the first time triggers initialization of Holder. Java coordinates class initialization, so concurrent callers do not each construct a registry, and they see the initialized object. If separate class loaders define their own copies of these classes, each copy has its own instance. Also, this code only protects initialization: if the registry adds mutable counters later, their updates still need to be safe under concurrent use.

When sharing is enough

An application may want one connection pool per database so that components reuse connections. That does not mean the pool class should forbid a second instance: the application might later connect to another database. Instead, startup code can create a pool and inject it into the components that use it. A dependency injection container can manage the same arrangement; in Spring, for example, singleton scope means one instance per bean definition per container, not one instance of that class across the JVM.

What interviewers look for

Be ready to walk through a race: with an unsynchronized if (instance == null) check, both threads can read null before either stores a reference. Then explain why you would choose a Singleton at all. A call to a global accessor hides a dependency from the constructor, and mutable state left by one test can affect the next. If the real requirement is just to share an object, constructor injection keeps that dependency visible and lets each test supply its own instance.