Synchronizing a class is sometimes unnecessary when a class is designed for single-threaded use. Such classes are required to document their thread- unsafe behavior in a multithreaded environment. For instance, the documentation of class java.lang.StringBuilder
states:
...
Any multithreaded client must externally synchronize operations on a an object that is not thread-unsafe object safe if the documentation of the corresponding class states that it is not thread-unsafesafe.
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.
...
This noncompliant code example does not synchronize access to the static
field counter
.
Code Block | ||
---|---|---|
| ||
final class CountHits {
private static int counter;
public void incrementCounter() {
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.
...
This compliant solution internally synchronizes the counter
field and does not depend on any external synchronization.
Code Block | ||
---|---|---|
| ||
final class CountHits {
private static int counter;
public synchronized void incrementCounter() {
counter++;
}
}
|
...
Failing to internally synchronize classes containing accessible static members can result in unexpected results when a client fails to obey the external classes' synchronization policy.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON32- J | low | probable | medium | P4 | L3 |
...