How to deal with Singleton along with Serialization

后端 未结 9 1612
感情败类
感情败类 2020-12-04 13:06

Consider I have a Singleton class defined as follows.

public class MySingleton implements Serializable{
 private static MySingleton myInstance;

 private MyS         


        
9条回答
  •  悲哀的现实
    2020-12-04 13:54

    The solution with enum won't work with Singletons managed by Spring, EJB, Guice or any other DI framework. It works only with enums, only because enum is treated specially by the serialization algorithm.

    Firstly, singletons don't need serialization, because if you deserialized it, and then deserialized singleton != YourSingleton.getInstance(), it would mean that you have two instances of your singleton, which means that YourSingleton isn't singleton at all, which may lead to unpredictable bugs.

    However sometimes you need to serialize non-singleton which contains a reference to singleton. The solution is easy:

    class NonSingleton implements Serializable {
        private transient YourSingleton singleton = YourSingleton.getInstance();
        ...
    }
    

    With Spring:

    @Configurable
    class NonSingleton implements Serializable {
        @Autowired
        private transient YourSingleton singleton;
        ...
    }
    

提交回复
热议问题