CodeBlanks Logo Icon CodeBlanks

Singleton

Learn to write the Singleton pattern in Java.

The Singleton pattern

The Singleton guarantees that a class has only one instance. This instance becomes application-wide: it is used for settings, caches, or a single log point.

It has three core parts: a private constructor prevents external new; a private static field holds the single instance; a public static getInstance method returns it. The instance is created on the first call; later calls return the same one.

Lazy and thread-safe

The simplest Singleton creates the instance on the first getInstance call (lazy init). But if several threads call at once, two instances may form. To prevent this you use synchronized or double-checked locking.

In Java the most robust way is sometimes an enum: enum Singleton { INSTANCE; }. Enum constants are naturally single-instance and thread-safe, so modern code often prefers an enum-based Singleton.

Practice Guarantee a single instance with Singleton

Write a Logger Singleton class with a private static Logger instance field, a private constructor, and a public static Logger getInstance() method (create the instance on the first call). In main, call getInstance twice and print the result of a == b with System.out.println.

Starter code

Main.java
// Define the Logger Singleton class
// Add a private constructor and getInstance
// Compare two instances in main

Sample solution

Main.java
class Logger {
    private static Logger instance;
    private Logger() { }
    public static Logger getInstance() {
        if (instance == null) instance = new Logger();
        return instance;
    }
}

public class SingletonDemo {
    public static void main(String[] args) {
        Logger a = Logger.getInstance();
        Logger b = Logger.getInstance();
        System.out.println(a == b);
    }
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Singleton parts

Term Meaning
private constructor Blocks new
private static field Holds the instance
getInstance Returns the instance
static Class-level access

2 Which element prevents creating a new instance with new from outside in a Singleton?

  • private constructor Correct answer
  • public static field
  • static getInstance
  • final field

Explanation: A private constructor blocks external new calls.

3 Complete the getInstance call

Question
Logger log = Logger.____();
Answer
Logger log = Logger.getInstance();

Explanation: getInstance returns the single instance.

All lessons in Advanced