Skip to main content
1 of 4
Ixrec
  • 27.7k
  • 15
  • 84
  • 87

When would a serializable singleton ever be useful?

I was reading Effective Java, and I came across passages that talk about ways you might implement a serializable singleton, as if this was a perfectly normal thing to do in Java. This immediately baffled me, because my intuition says that:

  • Being serializable necessarily implies value semantics.
  • Being a singleton necessarily implies identity semantics.
  • Value and identity semantics are mutually exclusive.

The Effective Java author even appears to share at least some of this intuition, if I'm reading this later passage correctly:

As a rule of thumb, value classes such as Date and BigInteger should implement Serializable, as should most collection classes. Classes representing active entities, such as thread pools, should rarely implement Serializable.

When I searched the book, this site and some blog posts, I found a lot of examples where readResolve() is little more than return INSTANCE;. Maybe I'm just really bad at Java, but a class like that looks to me as if it's saying "when deserializing an object of this class, ignore the serialized data completely and return the existing instance" which would imply the object is not actually serializable in any meaningful way. And yet there's this SO answer which seems to say "the only use for readResolve() is to make serializable singletons", so...that's about where I gave up and started writing this question.

Are there any huge misunderstandings in what I've said so far? If not, what would be a legitimate use case for a serializable singleton class? In particular, when would that be more useful than having a serializable class that's used in the interface of a separate singleton class?

Ixrec
  • 27.7k
  • 15
  • 84
  • 87