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

Reading List - 05-Mar-23

Talking to #AI may be the most important job skill of this century ( JohnGoodPasture ) Role of account management over the years. It’s a ro...