java singleton^immutable classes #enum

In c++ (and perhaps java) Most singletons are designed as “casual singletons” i.e. they are used as singletons, can be instantiated twice if you really want to, although there’s seldom a good justification.

[[effJava]] explains that an immutable class needs no copying. I think this is a performance view. (Does it apply to Optional.java? )

However, we don’t need to work hard trying to make it strict singletons.  Strict singleton is a functional requirement i.e. 2nd instance would be a functional defect.

If an immutable class happens to be used as one-instance data type, then lucky. But tomorrow it may get instantiated twice.. no worries 🙂

If boss asks you to make this class singleton, you should point out the legwork required and the numerous loopholes to fix before achieving that goal. Worthwhile?

Java enum types are special. JVM guarantees them to be immutable AND singleton, even in the face of serialization. See P 311.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s