...
Code Block |
---|
|
private final Boolean initialized = Boolean.FALSE;
public void doSomething() {
synchronized (initialized) {
// ...
}
}
|
...
Code Block |
---|
|
int lock = 0;
private final Integer Lock = lock; // Boxed primitive Lock is shared
public void doSomething() {
synchronized (Lock) {
// ...
}
}
|
Boxed types may 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 use of the boxed Integer
wrapper object is insecure; instances of the Integer
object constructed using the new
operator (new Integer(value)
) are unique and not reused. In general, holding a lock on any data type that contains a boxed value is insecure.
...
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 can cause maintenance problems because developers can incorrectly assume that boxed integers are appropriate lock objects. A more appropriate solution is to synchronize on a private final lock Object
as described in the following compliant solution.
...
Code Block |
---|
|
private final String lock = new String("LOCK").intern();
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
Wiki Markup |
---|
According to the Java API \[[API 06|AA. Java References#API 06]\] class {{java.lang.String}} documentation |
...
Code Block |
---|
|
// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String lock = "LOCK";
// ...
synchronized (lock) {
// ...
}
// ...
|
A String
literal is a constant and interned. Consequently, it suffers from the same pitfalls as the preceding noncompliant code example.
...
Code Block |
---|
|
private final String lock = new String("LOCK");
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
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 object instances or literals. A better approach is to synchronize on a private final lock object as shown in the following compliant solution.
...
Code Block |
---|
|
private final Object lock = new Object();
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
For more information on using an Object
as a lock, see CON04-J. Use private final lock objects to synchronize classes that may interact with untrusted code.
...