Singleton’s new Tinfoil Hat called “Don’t clone me!”
February 26, 2007 – 20:34 | javaI have been interviewing a number of folks to help filling up some Java developer positions. More than one of them (mind you, referred through different sources) told me, as part of the answer to “how would you implement a singleton?”, that I must override clone() to make sure my previous singleton wouldn’t get, well, cloned. And they all told me that they learned it “somewhere,” only unsure where that “somewhere” was.
I did some googling and actually found a couple of “Java tutorial” sites that tell people to override clone() as part of a “standard” singleton implementation. I won’t be linking to any of those sites for the obvious reason of not wanting to bump up their google rankings. And I’m just gonna post some kind of “counter-jinx” here:
If you are preparing for an interview, and happen to stumble upon this blog, please, please remember that Object.clone() by default throws CloneNotSupportException if the class does not implement Cloneable, and I don’t really think you would want to tell your interviewer that you wish to have your singleton class implementing Cloneable. So, no, it’s completely unnecessary to override the clone() method in a singleton implementation.

3 Responses to “Singleton’s new Tinfoil Hat called “Don’t clone me!””
I would implement a singleton as a bag of static things, unless it needed to implement some interface. That shows it for what it is commonly used for, a set of global variables.
Then I would remove it from my code, before the smell gets too bad.
Do I get the job?
By Ricky Clarkson on Feb 27, 2007
LOL, yes, Ricky, you can have my job.
I should have probably added that I ask that question a lot in interviews, not because I want to encourage singletons, but because it’s something most developers know about, and can act as a good platform for some more interesting follow-up questions regarding design patterns and multi-threading issues, etc.
By Jing Xue on Feb 27, 2007
Avoiding implementing Cloneable is easy. A bigger problem arises with Serializable. I could argue that it is sometimes necessary for a singleton to implement Serializable (though I could argue the flip side just as easily). Implementing cloning through in-memory (de)serialization is not only more robust, but ensures deep copying of fields. So… pop quiz. How does one prevent cloning of Serializable singletons.
Answer: Don’t try.
If you think of design patterns as something that makes your life easier, but you need to cooperate for it to work - you won’t be so concerned about playing Singleton-nazi.
Just put a caveat-emptor in your Javadoc and move on to the next candidate
By Howard D'Souza on Mar 2, 2007