This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Cloning a Singleton Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Cloning a Singleton Object" Watch "Cloning a Singleton Object" New topic
Author

Cloning a Singleton Object

Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
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


Thanks,
Alps
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Don't you think cloning a singleton would defeat the purpose of having a singleton in the first place? Is this a homework question?


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
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

Joined: Jul 26, 2007
Posts: 10167
    
    8

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

Joined: Oct 27, 2005
Posts: 19649
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Cloning a Singleton Object
 
Similar Threads
Tech Word Game
JMock with singleton object
Is StrutsPrepareAndExecuteFilter implemented as singleton pattern to process request
Singleton in a cluster
Creating a utility managed bean, to move common code and use from different beans?