The most popular implementation of this potter is as follows:

public class BillPughSingleton { private BillPughSingleton(){} private static class SingletonHelper{ private static final BillPughSingleton INSTANCE = new BillPughSingleton(); } public static BillPughSingleton getInstance(){ return SingletonHelper.INSTANCE; } } 

This option has a lazy initialization, but I don’t understand what makes it thread-safe, there’s no volatile and synchronize right there ... Could you explain?

    1 answer 1

    I myself am from the .NET world, but I can assume that the idea is similar.

    In this case, the runtime should be thread-safe, which should ensure that the class initializer will work safely in a multi-threaded environment (which means that during the execution of the initializer, some lock will be taken, which will give this guarantee).

    Here is a similar question on a large SO: Are Java static initializers thread safe?

    Yes, Java static initializers are thread safe (use your first option).

    However, you need to make sure that you can’t get it. Static initialization is performed once per class-loader.