Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added ThreadSafe detection

...

This noncompliant code example synchronizes on a Boolean lock object.

Code Block
bgColor#FFcccc

private final Boolean initialized = Boolean.FALSE;

public void doSomething() {
  synchronized (initialized) {
    // ...
  }
}

...

This noncompliant code example locks on a boxed Integer object.

Code Block
bgColor#FFcccc

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
bgColor#ccccff

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
bgColor#FFcccc

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
bgColor#FFcccc

// 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
bgColor#ccccff

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
bgColor#ccccff

private final Object lock = new Object();

public void doSomething() {
  synchronized (lock) {
    // ...
  }
}

...

Some static analysis tools can detect violations of this rule.

ToolVersionCheckerDescription
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V

CCE_CC_REUSEDOBJ_SYNC

Implemented

Bibliography

[API 2006]

Class String, Collections

[Findbugs 2008]

 

[Miller 2009]

Locking

[Pugh 2008]

Synchronization

[Tutorials 2008]

Wrapper Implementations

 

      08. Locking (LCK)