Java – about statically preserving monomer mode

According to the situation of volatile / lazy singles, eager singles, normal singles and through enum, I have developed singles, but specifically, I want to know the static holder mode singles as shown below

public static class Singleton {
    private static class InstanceHolder {
        public static Singleton instance = new Singleton();
    }

    private Singleton(){}

    public static Singleton getInstance() { 
        return InstanceHolder.instance;
    }
}

Please indicate which conditions are beneficial and what are their benefits

Solution

There are at least three reasons for this pattern:

>Static factory > lazy initialization thread safety

The JVM will delay initializing the instanceholder class until it is actually used, and since singleton is initialized with a static initializer, no additional synchronization is required The first call to getInstance through any thread will cause the instanceholder to be loaded and initialized. At this time, the initialization of singleton is carried out through the static initializer

The static bracket pattern is also considered to be the best alternative to the double locking anti mode

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>