The impact of deserialization on Java singleton

Solution: Let Singleton inherit Serializable and implement private Object readResolve();
public class Singleton implement Serializable { public static class Builder { public static Singleton instance = new Singleton(); } public static Singleton getInstance(){ return Builder.instance; } private Object readResolve(){ retutn Builder.instance; }}Copy the code
The principle of analytic

When deserializing, ObjectInputStream calls readObject –> readObject0 –> readOrdinary –> CheckResolve using reflection. InvokeReadResolve () is called in readOrdinady, which uses reflection to create new objects, thereby breaking singleton uniqueness. ### Respect copyright

The implementation of Java singleton pattern

#####1. Public class Singleton {

private static Singleton = new Singleton(); private Singleton() {} public static getSignleton(){ return singleton; }}Copy the code

#####2. lazy public class Singleton {// note the use of volatiile: 1. The second semantics of ensuring that the threshold is changed by the current thread in subsequent threads (visibility), and thread transparency in volatile, prohibit instruction reordering optimization. private static volatile Singleton singleton = null;

private Singleton(){} public static Singleton getSingleton(){ if(singleton == null){} synchronized (Singleton.class){ if(singleton == null){ singleton = new Singleton(); } } } return singleton; }}Copy the code

#####3. Static inner class public class Singleton {// Because static inner class is only loaded once, Private static class Holder {private static Singleton Singleton = new Singleton(); }

private Singleton(){} public static Singleton getSingleton(){ return Holder.singleton; }}Copy the code

#####4. Enumeration mode

public enum Singleton { INSTANCE; private String name; public String getName(){ return name; } public void setName(String name){ this.name = name; In addition to thread safety and preventing reflection from forcing calls to the constructor, enumerations provide an automatic serialization mechanism that prevents new objects from being created during deserialization. Therefore, Effective Java recommends using enumerations to implement singletons whenever possible.Copy the code