This week's giveaway is in the Threads forum.
We're giving away four copies of Java Concurrency Live Lessons and have Doug Schmidt on-line!
See this thread for details.
Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Cloning a Singleton Object  RSS feed

 
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
Bartender
Posts: 11445
18
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
Bartender
Posts: 11445
18
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
Posts: 20904
81
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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!