...
This noncompliant code example consists of the immutable Helper
class:
Code Block | ||
---|---|---|
| ||
// Immutable Helper
public final class Helper {
private final int n;
public Helper(int n) {
this.n = n;
}
// ...
}
|
and a mutable Foo
class:
Code Block | ||
---|---|---|
| ||
final class Foo {
private Helper helper;
public Helper getHelper() {
return helper;
}
public void setHelper(int num) {
helper = new Helper(num);
}
}
|
The getHelper()
method publishes the mutable helper
field. Because the Helper
class is immutable, it cannot be changed after it is initialized
. Furthermore, because Helper
is immutable, it is always constructed properly before its reference is made visible, in compliance with rule TSM03-J. Do not publish partially initialized objects. Unfortunately, a separate thread could observe a stale reference in the helper
field of the Foo
class.
...
This compliant solution synchronizes the methods of the Foo
class to ensure that no thread sees a stale Helper
reference.
Code Block | ||
---|---|---|
| ||
final class Foo {
private Helper helper;
public synchronized Helper getHelper() {
return helper;
}
public synchronized void setHelper(int num) {
helper = new Helper(num);
}
}
|
...
References to immutable member objects can be made visible by declaring them volatile.
Code Block | ||
---|---|---|
| ||
final class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void setHelper(int num) {
helper = new Helper(num);
}
}
|
...
This compliant solution wraps the mutable reference to the immutable Helper
object within an AtomicReference
wrapper that can be updated atomically.
Code Block | ||
---|---|---|
| ||
final class Foo {
private final AtomicReference<Helper> helperRef =
new AtomicReference<Helper>();
public Helper getHelper() {
return helperRef.get();
}
public void setHelper(int num) {
helperRef.set(new Helper(num));
}
}
|
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
VNA01-J | low | probable | medium | P4 | L3 |
Automated Detection
Some static analysis tools are capable of detecting violations of this rule.
Tool | Version | Description | ||||||
---|---|---|---|---|---|---|---|---|
ThreadSafe |
| Implemented |
Bibliography
...
Tasklist | ||||
---|---|---|---|---|
| ||||
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name||
|F|M|F|1270826173609| |dmohindr|"Unfortunately, a separate thread -could- *can* observe a stale reference in the helper field of the Foo class."|
|T|M|F|1270826698362|1271441478121|svoboda|"This compliant solution synchronizes the methods of *class* Foo -class- " (it sounds strange with class occuring after Foo)|
|