0

I understand that deserialization creates another instance of Singleton. But Why ? does it call private constructor internally ? On what instance does readResolve method is invoked, if the deserialized instance is a different instance altogether ?

Edit: This question is regarding traditional singleton which is not enum. The existing answer suggested is not same as it does not explain how readResolve is called internally. Hence, this question should not be marked as duplicate.

sumit sachdeva
  • 429
  • 3
  • 12

1 Answers1

0

The thing with de-serialization is: it is somehow black magic.

The JVM does it internally; and it works without calling any constructor. Basically it works like this:

  1. The JVM provides the "memory" that the object will require
  2. Then it takes the serialized bytes ... and puts them into your memory.

Therefore, yes; when you serialize a singleton; and de-serialize it within the same JVM, it is very well possible to create two objects representing the same singleton.

One of the many strange side effects of this kind of binary (de)serialization.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • I fail to understand how this ensures a different instance getting created. Also, on which instance does readResolve is called if the instance is different? – sumit sachdeva Aug 31 '16 at 15:27
  • Again: the JVM makes up **another** piece of memory; meaning: you end up with two different **references** pointing at two copies of the same singleton thingy. And, well, you got a nice duplicated answer - did you read that? – GhostCat Aug 31 '16 at 15:38
  • @sumitsachdeva What is to stop it? – user207421 Aug 31 '16 at 16:40