...
However, classes that use mutable static
fields must always internally synchronize accesses to their fields. This is because there is no guarantee that all clients will synchronize externally when accessing the field. Because a static
field is shared by all clients, unrelated clients may violate the contract by not performing adequate synchronization.
Noncompliant Code Example
This noncompliant code example does not synchronize access to the static
field counter
.
...
It relies on clients to externally synchronize the object and states its thread-unsafe behavior in the documentation. However, there is no guarantee that all unrelated (trusted or untrusted) clients will follow this advice.
Compliant Solution
This compliant solution internally synchronizes the counter
field and does not depend on any external synchronization.
Code Block | ||
---|---|---|
| ||
class CountHits { private static int counter; public synchronized void incrementCounter() { counter++; } } |
Risk Assessment
Failing to internally synchronize classes containing accessible static members can result in unexpected results when a client fails to obey the external synchronization policy.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON32- J | low | probable | medium | P4 | L3 |
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]\] \[[Bloch 08|AA. Java References#Bloch 08]\] Item 67: "Avoid excessive synchronization" |
...