Wiki Markup |
---|
Misuse of synchronization primitives is a common source of implementationconcurrency errorsissues. A significant number of concurrency vulnerabilities arise from locking on the wrong kind of object. An analysis of the JDK 1.6.0 source code unveiled at least 31 bugs that fell into this category \[[Pugh 08|AA. Java References#Pugh 08]\]. It is important to recognize the entities with whom synchronization is required rather than indiscreetly scavenging for variables or objects to synchronize on. |
...
This noncompliant code example uses a Boolean
field (initialized
) for synchronization.
Code Block | ||
---|---|---|
| ||
private final Boolean initialized = Boolean.FALSE; public void doSomething() { synchronized(initialized) { // ... } } |
...
Boxed types are allowed to use the same instance for a range of integer values and consequently, suffer from the same problem as Boolean
constants. If the value of the primitive can be represented as a byte, the wrapper object is reused. Note that the boxed Integer
wrapper object is shared and not an instance of the Integer
object (new Integer(value)
) itself. In general, holding a lock on any data type that contains a boxed value is insecure.
...