Note that there are some explanatory texts on larger screens.

plurals
  1. POEffective Java Item #77 - Serialization of singleton objects - Why should I have to use readResolve?
    primarykey
    data
    text
    <p><a href="http://www.amazon.co.uk/Effective-Java-Edition-Joshua-Bloch/dp/0321356683/ref=sr_1_1?ie=UTF8&amp;qid=1336435020&amp;sr=8-1" rel="nofollow">Effective Java</a> #77 states that we have to use <code>readResolve</code> to preserve the Singleton guarentee during serialization. They have used the example.</p> <pre><code>public class Elvis implements Serializable{ public static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public void leaveTheBuilding() { ... } </code></pre> <p>and they suggest using</p> <blockquote> <p>If the Elvis class is made to implement Serializable, the following readResolve method suffices to guarantee the singleton property:</p> </blockquote> <pre><code>// readResolve for instance control - you can do better! private Object readResolve() { // Return the one true Elvis and let the garbage collector // take care of the Elvis impersonator. return INSTANCE; } </code></pre> <blockquote> <p>This method ignores the deserialized object, returning the distinguished Elvis instance that was created when the class was initialized.</p> </blockquote> <ul> <li>Now the question is does serialization loads the class again to have two instance of Elvis? </li> <li>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</li> <li>From where does the other Elvis instance comes which is made eligble for garbage collection by readResolve (prevented from escaping the deserializtaion process). Can this be explained?</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload