This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Java in General and the fly likes singleton with clonable and deserialization?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "singleton with clonable and deserialization??" Watch "singleton with clonable and deserialization??" New topic

singleton with clonable and deserialization??

Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1281

what happen with singleton contract when singleton object is get cloned or deserialized in both the cases new object has been created...?


No Kaustubh No Fun, Know Kaustubh Know Fun..
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

what is your opinion regarding this?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20080

Kaustubh G Sharma wrote:in both the cases new object has been created...?

It depends.

The contract for Object.clone() specifically says that x.clone() == x is allowed, so if your singleton class needs to be Cloneable* you override clone() to return "this".

As for Serializable, if a singleton needs to be Serializable** then you should use the readResolve method. Look it up if you're not familiar with it.

Both will lead to the singleton object being used instead of a new object being created.

* and it usually shouldn't be. The only reason I can think of is when you are sub classing a Cloneable class.
** again, it usually shouldn't be. Again it should only be used if you are sub classing a Serializable class.

How To Ask Questions How To Answer Questions
Have you checked out Aspose?
subject: singleton with clonable and deserialization??
It's not a secret anymore!