Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

singleton with clonable and deserialization??

 
Kaustubh G Sharma
Ranch Hand
Posts: 1283
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what happen with singleton contract when singleton object is get cloned or deserialized in both the cases new object has been created...?

Kaustubh
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is your opinion regarding this?
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic