The Perfect Singleton

From time to time I met Java programmers that are not really sure how they should implement Singleton pattern properly.
(if you don’t have an idea what Singleton is just try Wikipedia: Singleton pattern).

And I’m not talking about proper implementation in threaded environment. But using most common implementation you find over internet you can easily create as many singletons as you like.
Just imagine you have common singleton implementation:

public final class NonSafeSingleton implements Serializable {

    private static final NonSafeSingleton INSTANCE = new NonSafeSingleton();

    private NonSafeSingleton() {}

    public static NonSafeSingleton getInstance() {
        return INSTANCE;
    }
}

Now concentrate on Serializable word. Think for one more second…
Yes you’re right. If you send this stuff over RMI you’ll get second instance.
It should even be enough to do some in memory serialization and de-serialization and kaboom! You’ve just blown away general Singleton contract.
That’s not very nice. But how to fix that? Generally there are two ways I use:

  1. The hard way (or you use 1.4 or older Java)

    You need to implement readResolve method in your Singleton class. This small thing is used to override what serialization mechanism has created.
    What you return there will be used instead of data that came from serialization (for details check: Serializable Javadoc). Just return your instance here:

    ...
        protected Object readResolve() throws ObjectStreamException {
            return INSTANCE;
        }
    ...
    

  2. The easy way (Yes, I’m using 1.5 or newer)

    Change your singleton class to enum and remove private constructor and getInstance method. Yes it’s really that simple. You get this for free then.

    public enum SafeSingleton implements Serializable {
    
        INSTANCE;
    }
    

Just keep this in mind when implementing next Singleton. It can make your life easier if you use RMI heavily.

About these ads

2 Responses to The Perfect Singleton

  1. Peter Koller says:

    Yes I see enum being used for singletons since some time. But that doesn’t feel right for me. enum is for typesave enumeration of values. Using its infrastructure like that is like using subclassing for code reuse. But maybe that’s just because I hate singletons.

  2. Marek Piechut says:

    I think you’re right in that it’s kind of misuse of enum keyword.

    It also has few other problems – it’s singleton forever, you cannot (unlike in regular version) change it to factory when needed, you cannot lazy initialize it. Instance retrieval is constant, no way to do any logging, caching, etc. But still, it’s the easiest way to get perfectly working singleton.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 29 other followers

%d bloggers like this: