File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "singleton with clonable and deserialization??" Watch "singleton with clonable and deserialization??" New topic
Author

singleton with clonable and deserialization??

Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1268

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

Kaustubh


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
Sheriff

Joined: Oct 27, 2005
Posts: 19557
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: singleton with clonable and deserialization??
 
Similar Threads
Tech Word Game
Is StrutsPrepareAndExecuteFilter implemented as singleton pattern to process request
Creating a utility managed bean, to move common code and use from different beans?
JMock with singleton object
Singleton & Factory