Fundamentals 7 min read

Various Singleton Pattern Implementations in Java

This article explains multiple Java singleton implementations—including eager initialization, static block, lazy initialization, double‑checked locking, static inner‑class holder, and enum—detailing their code, thread‑safety characteristics, advantages, and limitations such as reflection and serialization issues.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Various Singleton Pattern Implementations in Java

Singleton pattern ensures a class has only one instance and provides a global access point. This article presents several Java implementations, including eager initialization, static block initialization, lazy initialization, double‑checked locking, static inner‑class holder, and enum‑based singleton, with code examples and discussion of their advantages and drawbacks.

Eager Initialization

package com.renzhikeji.demo.singleton;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public final class EagerInitializedSingleton {
    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
    private EagerInitializedSingleton() {}
    public static EagerInitializedSingleton getInstance() {
        return instance;
    }
    public void method() {
        System.out.println(this);
    }
}

Mechanism: the instance is created when the class is loaded, guaranteeing thread safety without synchronization. Drawbacks: instance is created even if never used; vulnerable to reflection; initialization exceptions cannot be caught.

Static Block Initialization

package com.renzhikeji.demo.singleton;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public final class EagerInitializedSingleton {
    private static final EagerInitializedSingleton instance;
    static {
        try {
            instance = new EagerInitializedSingleton();
        } catch (Exception e) {
            throw new RuntimeException("Exception occured in creating singleton instance", e);
        }
    }
    private EagerInitializedSingleton() {
        System.out.println("init");
    }
    public static EagerInitializedSingleton getInstance() {
        return instance;
    }
    public void method() {
        System.out.println(this);
    }
}

Allows handling of exceptions during instance creation but shares the same drawbacks as eager initialization.

Lazy Initialization (Non‑Thread‑Safe)

package com.renzhikeji.demo.singleton;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public final class Singleton {
    private static Singleton instance;
    private Singleton() {
        System.out.println("init");
    }
    public static Singleton getInstance() {
        if (instance == null) {
            try {
                instance = new Singleton();
            } catch (Exception e) {
                throw new RuntimeException("Exception occured in creating singleton instance", e);
            }
        }
        return instance;
    }
    public void method() {
        System.out.println(this);
    }
}

Instance is created on first use, but the method is not thread‑safe and can be broken by reflection.

Double‑Checked Locking (Thread‑Safe)

package com.renzhikeji.demo.singleton;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public final class Singleton {
    private static volatile Singleton instance;
    private Singleton() {
        System.out.println("init");
    }
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    try {
                        instance = new Singleton();
                    } catch (Exception e) {
                        throw new RuntimeException("Exception occured in creating singleton instance", e);
                    }
                }
            }
        }
        return instance;
    }
    public void method() {
        System.out.println(this);
    }
}

First checks if the instance is initialized; if not, synchronizes and checks again before creating, reducing lock overhead. The volatile keyword prevents instruction reordering.

Static Inner‑Class Holder (Thread‑Safe)

package com.renzhikeji.demo.singleton;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public final class Singleton {
    private Singleton() {}
    public static Singleton getInstance() {
        return SingletonHelper.instance;
    }
    private static class SingletonHelper {
        private static final Singleton instance = new Singleton();
    }
    public void method() {
        System.out.println(this);
    }
}

The inner static class is not loaded until getInstance is called, providing lazy initialization with guaranteed thread safety without explicit synchronization.

Enum‑Based Singleton

package com.renzhikeji.demo.singleton;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public enum EnumSingleton {
    instance;
    public void method() {
        System.out.println(this);
    }
}

Enum singleton is inherently serializable and protects against reflection, but it does not allow lazy initialization.

All the above implementations can be compromised by reflection unless additional safeguards are added, and most (except the enum) require special handling to remain singleton during serialization and deserialization.

Key Takeaways

Understanding the concept and purpose of the singleton pattern.

Using Java modifiers ( final, private, static, volatile) to control inheritance, instantiation, and thread safety.

Choosing an implementation based on requirements for lazy loading, performance, and resistance to reflection/serialization attacks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javathread safetydesign patternSingleton
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.