permaculture playing cards*
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 Android Security Essentials Live Lessons this week in the Android 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: 1270

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: 19656

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
Don't get me started about those stupid light bulbs.
subject: singleton with clonable and deserialization??
Similar Threads
Tech Word Game
Creating a utility managed bean, to move common code and use from different beans?
JMock with singleton object
Is StrutsPrepareAndExecuteFilter implemented as singleton pattern to process request
Singleton & Factory