How to create a thread safe singleton in Java?

A singleton allows only one object of a class. The two simple and safe ways are:

public class Main {
    // 1. Holder idiom: lazy and thread safe, because class loading is thread safe
    static class Config {
        private Config() { System.out.println("Config created"); }

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

        static Config getInstance() { return Holder.INSTANCE; }
    }

    // 2. Enum singleton: also safe against reflection and serialization
    enum Registry {
        INSTANCE;
        int counter;
    }

    public static void main(String[] args) {
        System.out.println("Start");
        Config a = Config.getInstance();
        Config b = Config.getInstance();
        System.out.println(a == b);

        Registry.INSTANCE.counter++;
        System.out.println(Registry.INSTANCE.counter);
    }
}
Output

Start
Config created
true
1

The object is created when it is used the first time, and only once. Other common ways are double checked locking with a volatile field, but the two above are simpler.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.