Java study notes - Singleton

Outline

Singleton is a creator mode. When we need to ensure that the system only exists a class of an object, such as: class global information such as when we start a project profile for the instance of the read class thereby reading a configuration Config by business logic operation target , stateless tools is only one instance can be multiplexed, that is, when the limit is only one instance of an object can be made or security reasons and repeatedly create the instance consumes system resources, then you can use singleton.

Implementation

When implementing a singleton class, as it relates to the class load, create object properties, access to object properties and other issues, need to take into account the object creation time, create assignments of the thread-safe, to prevent reflection and object serialization caused Examples are multi-like.

Eager hungry Chinese-style

Hungry man is the simplest type of Singleton object properties in the class when the class loader is initialized, because the single-threaded to ensure that the JVM load the class, so avoid threading issues, but even during operation resulting in the whole not eager loading use of this class will be loaded, resulting in unnecessary waste of resources.

public class Singleton {
    
    private static Singleton singleton = new Singleton();
    
    private Singleton {}
    
    public static Singleton getInstance() {
        return singleton;
    }
}

Equivalent codes

public class Singleton {
    
    private static Singleton singleton;
    
    static {
        singleton = new Singleton();
    }
    
    private Singleton {}
    
    public static Singleton getInstance() {
        return singleton;
    }
}

Lazy lazy loading

I.e., lazy loading of singleton class is instantiated, but does not consider the simple lazy loading security thread in use, in getInstance()the method, if two threads into the instance of the object is equal to nullthe ifstatement, the object will be instantiated twice thus violating singleton pattern in mind.

//  线程不安全的懒加载单例类代码
public class Singleton {
    
    private static Singleton singleton;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if(singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}
// 重量级锁线程安全的懒加载单例类实现
public class Singleton {
    
    private static Singleton singleton;
    
    private Singleton() {}
    
    public static synchronized Singleton getInstance() {
        if(singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}
// 方法内部锁线程安全的懒加载单例类实现(双重检查)
public class Singleton {
    
    // 由于实例化对象非原子操作,所以加volatile
    private static volatile Singleton singleton;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        // 第一次判断让实例构造完成后能并发执行
        if(singleton == null) {
            synchronized (Singleton.class) {
                // 第二次判断防止第一次判断同时进入多个线程
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
// 静态内部类懒汉式写法
public class Singleton {
    
    private Singleton() {}
    
    // 使用了静态内部类,让JVM在类加载也就是内部类被Singleton.getInstance()方法内调用时时为我们初始化
    private static class SingletonInstance {
        private static final Singleton singleton = new Singleton();
    }
    
    public static Singleton getInstance() {
        return SingletonInstance.singleton;
    }
}

Enum enumeration type

Enumeration type is used javain the form of an enumeration class constructor singleton class, enum type in guaranteed lazily thread-safe (enumerable object is staticin the form of initialization, JVM thread-safe) at the same time, because the javaprovisions in pieces For objects only output serialization name, deserialization is used nameto find the object, so as to achieve a single embodiment instead of being destroyed. In reflection, because newInstance()the user attempting to create enuman object type is checked so that when an error, it is very safe.

// 枚举式实现Resource的单例,通过Something.INSTANCE.getInstance()即可访问
class Resource{

}

public enum Something {
    
    INSTANCE;
    
    private Resource instance;
    
    Something() {
        instance = new Resource();
    }
    
    public Resource getInstance() {
        return instance;
    }
}

to sum up

Binding many factors, can simultaneously achieve lazy loading, security thread, stop sequence deserialization reflective destruction is the best embodiment of a single enumeration of single mode embodiment implemented.

Guess you like

Origin www.cnblogs.com/camwang/p/12114833.html
Recommended