Monday, April 26, 2010

what will happen if I serialize and de-serialize a singleton instance in same JVM?

what will happen if I serialize and de-serialize a singleton instance in same JVM?

We will get two instances of Singleton object. To avoid that we should use a readResolve() method which returns the singleton instance.


Implementing a Serializable Singleton:

public class MySingleton implements Serializable
{
static MySingleton singleton = new MySingleton();
private MySingleton() {
}
// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve()
{
return singleton;
}
}


You might also like ..


SHARE & SAVE
Delicious Digg Furl Stumbleupon Technorati Squidoo Reddit live Yahoo MySpaceGoogle Yahoo Buzz Facebook Twitter Orkut Google Buzz Email this postby bbP

No comments: