...
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 primitive can be represented as a byte, the wrapper object is reused. Note that the boxed Integer
primitive 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.
...
This compliant solution locks on a non-boxed Integer. The doSomething()
method synchronizes using the intrinsic lock of the Integer
instance, Lock
.
Code Block | ||
---|---|---|
| ||
int lock = 0;
private final Integer Lock = new Integer(lock);
public void doSomething() {
synchronized(Lock) {
// ...
}
}
|
When explicitly constructed, an Integer
object has a unique reference and its own intrinsic lock that is not shared with other Integer
objects or boxed integers having the same value. While this is an acceptable solution, it may cause maintenance problems. It is always better to synchronize on a internal private final raw Object
as described next.
Compliant Solution (internal private final
...
raw Object
)
This compliant solution uses an internal private final lock object. This is one of the few cases where a raw Object
is useful.
...
Consequently, an interned String
object behaves like a global variable in the JVM. As demonstrated in this noncompliant code example, even if every instance of an object maintains its own field lock
, the field points to a common String
constant in the JVM. Trusted code that locks on the same String
constant renders all synchronization attempts inadequate. Similarly, hostile code from any other package can exploit this vulnerability if the class is accessible.
Noncompliant Code Example (String
literal)
...
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 objects or literals. A more suitable approach is to use the private final internal raw Object
an internal private lock as discussed earlier.
Noncompliant Code Example (getClass()
lock object)
...