We keep reading about how to use ‘readResolve()’ to ensure singleness in case of serializing a Singleton. But what are practical use cases for wanting to serialize a Singleton in the first place?
EDIT: pl. note: the question is about why to serialize a Singleton, and not about what’s a safe way to do so.
The object may be a singleton, but it may be part of a larger structure which doesn’t quite know it is. For example, it may implement an interface which can have several different implementations (and thus, instances):
Now, let’s say we want a
StringSinkwhich dumps strings to stdout. Since there’s only one stdout, we might as well make it a singleton:And we use it like this:
If you were to serialize, and then deserialize this dumper, you’d have two
StdoutStringSinkinstances floating around in your program.