transient for serializing singleton

后端 未结 3 606
醉酒成梦
醉酒成梦 2020-12-18 17:18

Effective Java - To maintain the singleton guarantee, you have to declare all instance fields transient and provide a \'readResolve\' method. What do we achieve by declaring

3条回答
  •  情书的邮戳
    2020-12-18 17:44

    What you gain by making the attribute transient is that you don't serialize the state. Serializing it is unnecessary, since it's discarded anyway by the readResolve() method.

    If the state consists in an int, it doesn't matter much. But if the state is a complex graph of objects, it makes a significant performance difference. And of course, if the state is not serializable, you don't have any other choice.

    That said, serializing a singleton is questionable.

提交回复
热议问题