Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
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
bgColor#FFcccc
// This bug was found in jetty-6.1.3 BoundedThreadPool
private final String _lock = "LOCK";

// ...
  synchronized(_lock) { 
    // ...
  }
// ...

A String literal is a constant and is interned. Consequently, it suffers from the same pitfalls as the preceding noncompliant code example.

...

Code Block
bgColor#ccccff
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 an internal private final lock object as shown in the following compliant solution.

...