Effective Java Item #77 - Serialization of singleton objects - Why should I have to use readResolve?

后端 未结 3 895
刺人心
刺人心 2020-12-10 23:15

Effective Java #77 states that we have to use readResolve to preserve the Singleton guarentee during serialization. They have used the example.

         


        
3条回答
  •  自闭症患者
    2020-12-10 23:54

    • Now the question is does serialization loads the class again to have two instance of Elvis?

    A new instance of Elvis is created (the impersonator), but the overloaded readResolve method ensures that it is not returned as part of the data structure returned by ObjectInputStream.readObject().

    The Elvis impersonator is (or soon becomes) unreachable, and is garbage collected.

    • If the class is loaded only once then we should be having only one instance of Elvis since static fields are not serialized and are not restored during deserialization and

    Ideally yes. In practice no.

    • From where does the other Elvis instance comes which is made eligible for garbage collection by readResolve (prevented from escaping the deserialization process). Can this be explained?

    The deserialization process starts out by creating the 2nd Elvis (the impersonator), but the readResolve method ensures that nothing ever sees it.

    To understand how and why that is the case, you need to understand the function that a readResolve() method plays in deserialization, as specified here. Basically, when the readResolve() method returns INSTANCE it is saying, "wherever you were going to use the impersonator in the graph we are building, use the real Elvis instead".

提交回复
热议问题