Skip to content
Veltoryx Technologies
ProLesson 4.1Intermediate8 min readUpdated 31 October 2026

Singleton Pattern

Learn how to guarantee exactly one instance of a class, the safe ways to write it in Java, why it is often overused, and how a framework like Spring gives you the same result more cleanly.

A country has one president or prime minister at a time. A school has one principal. A computer has one print queue that all programs share. In each case, having two of them would cause confusion: two principals giving different orders, or two print queues sending pages in a mess.

Some things in a program are the same. There should be one configuration object that holds the settings, one logger that writes to the log file, one pool of database connections. The Singleton pattern is a way to make sure that exactly one object of a class exists, and that everyone can reach it.

This is the first of the creational patterns, the group of patterns that is about how objects are created. You will meet five of them in this module. Singleton is the most famous, and also the most misused, so it is worth understanding both its strength and its dangers.

01The problem

Suppose three services in your application need the application settings:

Each service creates its own copy
public class AppConfig {
    private final Properties values = new Properties();

    public AppConfig() {
        /* read the settings file from disk */
    }

    public String get(String key) { return values.getProperty(key); }
}

// In three different services
AppConfig configA = new AppConfig();
AppConfig configB = new AppConfig();
AppConfig configC = new AppConfig();

This has three problems:

  • The settings file is read three times, which wastes time and memory.
  • If one copy is changed at run time (for example a feature flag is switched), the other two copies do not know, and the services disagree.
  • Anyone can create a fourth copy at any time, and the problem returns.
Without Singleton each service creates its own copy; with Singleton all services share one object
Fig. 1 · Without Singleton each service creates its own copy; with Singleton all services share one object

Loading the rest of the lesson…