...
If the Helper
class is immutable, it cannot be changed after it is initialized and will always be properly constructed. However, this does not prevent a thread from accessing the helper
field of class Foo
such that it misses observing the most recent value set by some other thread.
Compliant Solution (synchronization)
This compliant solution synchronizes the methods of class Foo
to ensure that no thread sees a partially initialized helper
.
Code Block | ||
---|---|---|
| ||
class Foo { private Helper helper; public synchronized Helper getHelper() { return helper; } public synchronized void initialize(int num) { helper = new Helper(num); } } |
Compliant Solution (volatile
)
Immutable members can also be safely published by declaring them volatile
as described in CON00-J. Declare shared variables as volatile to ensure visibility and prevent reordering of accesses.
Code Block | ||
---|---|---|
| ||
class Foo {
private volatile Helper helper;
// ...
}
|
Risk Assessment
The assumption that classes containing immutable objects are immutable is misleading and can cause serious thread-safety issues.
...