...
This noncompliant code example synchronizes on a Boolean
lock object.
Code Block | ||
---|---|---|
| ||
private final Boolean initialized = Boolean.FALSE;
public void doSomething() {
synchronized (initialized) {
// ...
}
}
|
...
This noncompliant code example locks on a boxed Integer
object.
Code Block | ||
---|---|---|
| ||
int lock = 0;
private final Integer Lock = lock; // Boxed primitive Lock is shared
public void doSomething() {
synchronized (Lock) {
// ...
}
}
|
...
This compliant solution locks on a nonboxed Integer
, using a variant of the private lock object idiom. 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) {
// ...
}
}
|
...
This noncompliant code example locks on an interned String
object.
Code Block | ||
---|---|---|
| ||
private final String lock = new String("LOCK").intern();
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
...
This noncompliant code example locks on a final String
literal.
Code Block | ||
---|---|---|
| ||
// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String lock = "LOCK";
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
...
This compliant solution locks on a noninterned String
instance.
Code Block | ||
---|---|---|
| ||
private final String lock = new String("LOCK");
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
...
This compliant solution synchronizes on a private final lock object. This is one of the few cases in which a java.lang.Object
instance is useful.
Code Block | ||
---|---|---|
| ||
private final Object lock = new Object();
public void doSomething() {
synchronized (lock) {
// ...
}
}
|
...
Some static analysis tools can detect violations of this rule.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
ThreadSafe |
| CCE_CC_REUSEDOBJ_SYNC | Implemented |
Bibliography
[API 2006] | Class String, Collections |
| |
Locking | |
Synchronization | |