...
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 . . . } |
By applying a static modifier to the getInstance()method which returns the Singleton, allows the method to be accessed subsequently without creating a new object.
Risk Assessment
Using lazy initialization of a Singleton without synchronizing the getInstance()method may lead in multiple instances.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the Java Secure Coding Standard as MSC05-J. Make your classes non Cloneable unless required
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 17, Threads and Locks|http://java.sun.com/docs/books/jls/third_edition/html/memory.html] |
...