Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloning a Singleton Object

 
Alpesh Rathod
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I just wanted to know that is it possible to clone a singleton object ....if yes then y??
If the object is a singleton, then what measures need to be taken so that only single instance of it exists?





Regards,
Alps
 
Maneesh Godbole
Saloon Keeper
Posts: 11070
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't you think cloning a singleton would defeat the purpose of having a singleton in the first place? Is this a homework question?
 
Alpesh Rathod
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well in that case if someone tries cloning a singleton object then.......

In that case i think we should provide a clone method which throws a CloneNotSupportedExcption in our Singleton class....so anyone if at all tries to clone the singleton oject.. would get a exception...and in this way tha object wont be cloned..
 
Maneesh Godbole
Saloon Keeper
Posts: 11070
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alpesh Rathod wrote:
In that case i think we should provide a clone method which throws a CloneNotSupportedExcption in our Singleton class....


You do not need to do anything.
From the Cloneable API docs (emphasis added)
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will need to throw an exception if your singleton class extends (directly or indirectly) another class that does implement Cloneable. Throwing a CloneNotSupportedException yourself is a valid solution - just remember to document it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic