...
The Boolean
type is unsuitable for locking purposes because it allows only two values: true and false. Boolean literals containing the same value share unique instances of the Boolean
class in the JVM. In this example, initialized
references the instance corresponding to the value false. If any other code inadvertently synchronizes on a Boolean
literal with the value FALSE
false, the lock instance is reused and the system can become unresponsiveness or deadlocked.
...
A String
instance differs from a String
literal. The instance has a unique reference and its own intrinsic lock that is not shared by other string
String
object instances or literals. A better approach is to synchronize on a private final lock object as shown in the following compliant solution.
...
Wiki Markup |
---|
\[[API 2006|AA. Java References#API 06]\] Class String, Collections \[[Findbugs 2008|AA. Java References#Findbugs 08]\] \[[Miller 2009|AA. Java References#Miller 09]\] Locking \[[Pugh 2008|AA. Java References#Pugh 08]\] "Synchronization" \[[Tutorials 2008|AA. Java References#Tutorials 08]\] [Wrapper Implementations|http://java.sun.com/docs/books/tutorial/collections/implementations/wrapper.html] |
Automated Detection
The following table summarizes the examples flagged as violations by FindBugs:
Noncompliant Code Example | Flagged | Checker | Message |
---|---|---|---|
| Yes | DL_SYNCHRONIZATION_ON_BOOLEAN | Synchronization on Boolean could deadlock |
Boxed primitive | Yes | DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE | Synchronization on Integer could deadlock |
interned | No | n/a | n/a |
| Yes | DL_SYNCHRONIZATION_ON_SHARED_CONSTANT | Synchronization on interned String could deadlock |
Related Vulnerabilities
Any vulnerabilities resulting from the violation of this rule are listed on the CERT website.
...