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 reference 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
Serializable, as should most collection classes. Classes representing active entities, such as thread pools, should rarely implement
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, and what would its semantics be?