跪拜 Guibai
← Back to the summary

Singleton in Java and Kotlin: From Eager to Enum, Plus a Thread-Safe ToastManager

Singleton Design Pattern: From Java/Kotlin Implementations to Android Practice

What is a Design Pattern?

Design patterns are a set of proven software design solutions used to solve common problems in software development, improving code reusability, maintainability, and extensibility.

That is the definition of a design pattern. Simply put, it is a set of development ideas that solve specific scenario-based problems. It is a set of ideas, not a fixed template. As long as the idea is consistent, it can be considered the same pattern.

Next, we start with the most common singleton design pattern.

Common Implementations of the Singleton Design Pattern

The singleton design pattern ensures that a class has only one instance throughout the entire program and provides an entry point to obtain that instance. For example, log classes, thread pools, and various management classes are well suited to this pattern.

Below are several common implementations, starting with the simplest eager initialization.

Eager Initialization: Created at Class Loading

How to implement it?

  1. Privatize the constructor to prevent external creation of instances.
  2. Provide a static method for external callers to obtain the instance.

Here is the Java code first:

public class Singleton {
    // 1. Private constructor, with only one constructor
    private Singleton() {
    }

    // 2. The instance held internally
    private static final Singleton instance = new Singleton();

    // 3. Provide a method to get the internally held instance
    public static Singleton getInstance() {
        return instance;
    }
}

This completes the simplest singleton, which is eager initialization. The instance is created directly when the class is loaded.

This approach is simple and inherently thread-safe. However, it has a drawback: as long as the class is loaded (for example, by calling other static methods or accessing static fields), even if getInstance() is never called, the instance will be created prematurely. If the instance initialization has a high cost, it can waste memory or slow down program startup.

Lazy Initialization and Double-Checked Locking (DCL): Load on Demand

With that in mind, we can switch to lazy initialization: only create the instance when it is actually needed. Like this:

public class Singleton {
    private Singleton() {
    }

    private static Singleton instance;

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

This is the basic lazy singleton, but it has a bug: in a multithreaded concurrency scenario, more than one thread can enter the if statement at the same time, resulting in multiple instances being created.

How to solve this? The most direct solution is to add a lock to the getInstance method:

public static synchronized Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}

However, locking the entire method has poor performance; every call to get the instance has to go through the synchronized lock. So in real development, DCL (Double-Checked Locking) is typically used to solve this problem:

For more details on double-checked locking (DCL), see my blog post: Java Multithreading Guide: From Basic Usage to Thread Safety

// volatile prevents instruction reordering
private static volatile Singleton instance;

private static final Object instanceLock = new Object();

public static Singleton getInstance() {
    if (instance == null) {
        synchronized (instanceLock) {
            if (instance == null) {
                // The inner check prevents multiple threads from reacquiring the lock and creating duplicate instances
                instance = new Singleton();
            }
        }
    }
    return instance;
}

This approach balances efficiency and thread safety. Typically, the lock is only used on the first call to get the instance; subsequent calls skip the outer check entirely.

Why Must DCL Use volatile?

Note: synchronized ensures mutual exclusion and visibility within the synchronized block, but it cannot prevent instruction reordering inside the block. The outermost if (instance == null) is outside the synchronized block, so you must add the volatile keyword to instance to forbid instruction reordering and guarantee ordering.

Of course, volatile also guarantees visibility, but here its main role is ordering.

Why is instruction reordering a problem?

Because instance = new Singleton(); actually splits into three steps at the low level:

  1. Allocate a block of memory to store the Singleton object's data.
  2. Initialize the object, assigning values to the properties in memory.
  3. Point the instance variable to this memory block.

In the JVM, the order of steps 2 and 3 is not fixed. If reordering occurs, a scenario like this can appear: thread A executes steps 1 and 3 (at this point instance is not null, but the object is not yet initialized), and another thread checks instance != null at the outer level, and directly returns it. As a result, the caller gets a "half-finished" object, which causes problems when used.

Static Inner Class: Elegant Lazy Loading

The static inner class is also a common singleton implementation:

public class Singleton {
    private Singleton() {
    }

    private static class InnerHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return InnerHolder.INSTANCE;
    }
}

This also qualifies as lazy loading—only when getInstance() is called does the InnerHolder class get loaded, and then the instance is created. The class loading process is guaranteed thread-safe by the JVM, and there is no lock overhead.

Enum Singleton: The Most Secure Implementation

The enum singleton is also recognized as the most secure:

public enum Singleton {
    INSTANCE;

    // Business code
}

It is similar to eager initialization, but has two advantages:

Singleton in Kotlin: object and by lazy

In Kotlin, of course, the simplest singleton implementation is object ClassName:

object KotlinSingleton {
    val now = System.currentTimeMillis()
}

What does this mean?

Use the IDE's tool to view the bytecode, click to decompile, and you'll see the corresponding Java code similar to this:

public final class KotlinSingleton {
   @NotNull
   public static final KotlinSingleton INSTANCE = new KotlinSingleton();
   private static final long now = System.currentTimeMillis();

   private KotlinSingleton() {
   }

   public final long getNow() {
      return now;
   }
}

You can see that object is essentially eager initialization. The compiler automatically generates a static INSTANCE field for the class. companion object is similar; feel free to decompile the bytecode yourself to see.

Additionally, if you need a lazy-loaded singleton in Kotlin, don't copy the Java implementation directly—it will look awkward. Instead, use companion object with by lazy:

class KotlinLazySingleton private constructor() {
    companion object {
        // by lazy defaults to SynchronizedLazyImpl, which is essentially double-checked locking (DCL)
        val instance: KotlinLazySingleton by lazy {
            KotlinLazySingleton()
        }
    }
}

Android Practice: Encapsulating a Global ToastManager

Finally, let's use the singleton pattern to encapsulate a Toast management class.

The requirement is: support safe calls from child threads, and when multiple Toasts are triggered consecutively (e.g., by rapid clicks), only the latest message should be shown—that is, cancel the previous message before showing the next one.

public class ToastManager {
    private ToastManager() {
    }

    private static volatile ToastManager mInstance;
    private static final Object mInstanceLock = new Object();

    public static ToastManager getInstance() {
        if (mInstance == null) {
            synchronized (mInstanceLock) {
                if (mInstance == null) {
                    mInstance = new ToastManager();
                }
            }
        }
        return mInstance;
    }

    // Above is the singleton implementation

    private Context mAppContext;
    private Toast mToast;
    private final Handler mMainHandler = new Handler(Looper.getMainLooper());

    public void init(Context context) {
        if (context != null) {
            mAppContext = context.getApplicationContext();
        }
    }

    private boolean isMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    public void show(String message, int duration) {
        if (mAppContext == null) {
            throw new IllegalStateException("ToastManager is not initialized.");
        }
        show(mAppContext, message, duration);
    }

    public void show(Context context, String message, int duration) {
        if (context == null) {
            return;
        }
        // Always convert to ApplicationContext to prevent mToast from indirectly holding an Activity and causing memory leaks
        Context appContext = context.getApplicationContext();
        if (!isMainThread()) {
            mMainHandler.post(() -> showInternal(appContext, message, duration));
        } else {
            showInternal(appContext, message, duration);
        }
    }

    private void showInternal(Context appContext, String message, int duration) {
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(appContext, message, duration);
        mToast.show();
    }

    /**
     * Cancel the currently displayed or queued toast
     */
    public void cancel() {
        mMainHandler.removeCallbacksAndMessages(null);
        if (isMainThread()) {
            cancelInternal();
        } else {
            mMainHandler.post(this::cancelInternal);
        }
    }

    private void cancelInternal() {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
    }
}

Usage example:

public class DemoApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ToastManager.getInstance().init(this);
    }
}
new Thread(() -> {
    ToastManager.getInstance().show("Hello, World!", Toast.LENGTH_SHORT);
}).start();
Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

booboosui 1 likes

Next to DCL, there's another pitfall that's easier to trip on: top-level val is initialized in file order, not dependency order. What I stepped on was writing the singleton object in the upper part of the file and the config constants below; compilation passes all the way, but at runtime the object reads an empty string for the constant. This has nothing to do with volatile; it's an ordering issue: file-level vals compile into static fields, assigned in declaration order, so anything running earlier only sees the default value of something declared later, and the compiler stays quiet. The verification method is crude: move the entire constants section before the object; if behavior changes, that's it.