The Java Singleton pattern is a design pattern that governs the instantiation process. According to this design pattern, there can only be one instance of your class per JVM at any time.
The most usual implementation of a Singleton in Java is done by having a single instance of the class as a static field.
You can create that instance using lazy initialization, which means that the instance is not created when the class loads, but when it is first used.
Noncompliant Code Example
When the getter method is called by two threads or classes simultaneously can lead in multiple instances of the singleton class if you neglect to use synchronization, which is a common mistake that happens with that implementation.
public class MySingleton { private static MySingleton _instance; private MySingleton() { // construct object . . . } // error, no synchronization public static MySingleton getInstance() { if (_instance==null) { _instance = new MySingleton(); } return _instance; } // Remainder of class definition . . . }
Compliant Solution
This compliant solution uses notifyAll()
which sends notifications to all threads that wait on the same object. As a result, liveness is not affected unlike the noncompliant example. Ensure that the lock is released promptly after the call to notifyAll()
.
else if(number == 3) { Thread.sleep(2000); list.notifyAll(); }
Risk Assessment
To guarantee the liveness of a system, the method notifyAll()
should be called rather than notify()
.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
CON32-J |
low |
unlikely |
medium |
P2 |
L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[JLS 05]] Chapter 17, Threads and Locks
[[Goetz 06]] Section 14.2.4, Notification
[[Bloch 01]] Item 50: Never invoke wait outside a loop
CON31-J. Always invoke the wait() method inside a loop 08. Concurrency (CON) 09. Methods (MET)