Singleton with transient field
932135Apr 21 2012 — edited Apr 21 2012Hi experts,
I was reading about different ways of implementing Singleton pattern. In Effective Java 2, it has been suggested Enum is the best way to implement a Singleton.Yes i accept that. But if I want to have transient fields in it or if I have some state in it, when Serialized/deserialized enum will not retain the value.
In this case if we implement Singleton without Enum, assume I am going for adding a method to return the instance after double lock(lazy loading) and override readobject method, we will be able to read transient fields. But when some one calls this class to getInstance, wont it result in 2 objects getting created.
1. Deserialized object
2. The new object through getInstance
Wont this beat Singleton principle.
If this is the case should we say in order to maintain a Singleton guaranteed the class should be immutable?