...
Code Block | ||
---|---|---|
| ||
public class MySingleton { private static MySingleton _instance; private MySingleton() { // construct object . . // private constructor prevents instantiation by outside callers } // lazy initialization public static synchronized MySingleton getInstance() { if (_instance==null) { _instance = new MySingleton(); } return _instance; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } // Remainder of class definition . . . } |
See MSC05- J Make your classes non Cloneable unless required for more details about restricting the clone()
method.
Risk Assessment
Using lazy initialization of a Singleton without synchronizing the getInstance()method may lead in multiple instances.
...