...
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 is 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 an internal private final lock object as shown in the following compliant solution.
...