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) {

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?


Rajneesh Garg said...

You can also check out Implementing a Serializable Singleton.

trinity said...

I really liked the info on your site about software testing - nice work. I've just started my own software testing secrets blog and would really appreciate you stopping by

Anonymous said...

Hi rajneesh,

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


Popular Posts (Last 30 days)

This is a personal blog and I do not speak for my employer.