Static inner class singleton pattern

public class SingletonInner {
    private static class Holder {
        private static SingletonInner singleton = new SingletonInner();
    }

    private SingletonInner(){}

    public static SingletonInner getSingleton(){
        return Holder.singleton;
    }
}

    Inner classes are divided into object level and class level. Class-level inner classes refer to inner classes with statically modified member variables. An inner class without statically modified member variables is called an object-level inner class.

A class-level inner class is equivalent to a static member of its outer class. There is no dependency between its objects and the outer class objects, and they are independent of each other, so they can be created directly. An instance of an object-level inner class must be bound to an instance of an outer object. Class-level inner classes are loaded only the first time they are used.

To easily achieve thread safety, you can use the static initializer method, which can ensure thread safety by the JVM, such as a villain-style singleton. This implementation method will initialize the object when the class is loaded. It is possible to waste a certain amount of memory (assuming you don't need it), there is a way to make the class load without initializing the object, that is to use a class-level inner class, and create object instances in this class-level inner class.

 

When the getInstance method is called for the first time, it reads SingletonHolder.instance for the first time, and the inner class SingletonHolder class is initialized; and when this class is loaded and initialized, its static field will be initialized, thereby creating a Singleton The instance, because it is a static domain, is only initialized once when the virtual machine loads the class, and the virtual machine ensures its thread safety.

The advantage of this pattern is that the getInstance method is not synchronized and only performs a field access, so lazy initialization does not add any access cost.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325173128&siteId=291194637