Wednesday, September 21, 2005

Serializing a Singleton

I have been forwarded some study material on Core Java related stuff from The Training Group in my Organization to prepare for a forthcoming training program. While going thro it, I came across an interesting point of which I was unaware earlier. It relates to Singleton classes. While dicussing Singleton classes, it says that
To make a singleton class serializable provide a readResolve method. Otherwise, each deserialization of a serialized instance will result in the creation of a new instance.

public class CacheMgr {
public static final CacheMgr INSTANCE = new CacheMgr();

private CacheMgr() {
// ...
}

// ... // Remainder omitted

// readResolve method to preserve singleton property
private Object readResolve() throws ObjectStreamException {
/*
* Return the one true CacheMgr and let the garbage collector
* take care of the CacheMgr impersonator.
*/
return INSTANCE;
}

public static void main(String[] args) {
System.out.println(CacheMgr.INSTANCE);
}
}


I have not thought of this aspect so far. So, obviously, I have no experience of it either. However, I am interesting to know if you know an idea on the subject. Any first hand experience?

2 comments:

Rajneesh Garg said...

You can also check out Implementing a Serializable Singleton.

Anonymous said...

Hi rajneesh,

Please guide me step by step installation on WinXp..
Apache config : please provide config in detail....

Total Pageviews

Diving into the Controversial World of IPL with Lalit Modi

Lalit Modi, the mastermind behind the Indian Premier League (IPL), recently had a candid interview with Raj Shamani. The interview delved d...