...
It is unreasonable to assume that classes that use immutable objects are themselves immutable.
Noncompliant Code Example
This noncompliant code example publishes the helper
field prematurely through the getHelper()
method. Multiple threads may initialize the field, making class Foo
mutable.
...
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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON28-J | low | probable | medium | P4 | L2 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] \[[JPL 06|AA. Java References#JPL 06]\], 14.10.2. Final Fields and Security: |
...