Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Singleton with transient field

932135Apr 21 2012 — edited Apr 21 2012
Hi 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?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 19 2012
Added on Apr 21 2012
8 comments
660 views