You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

Synchronizing a class is sometimes unnecessary when a class is designed for single-threaded use. Such classes are required to document their unsafe behavior in a multithreaded environment. For instance, the documentation of class java.lang.StringBuilder states:

This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Any multithreaded client must externally synchronize operations on an object that is not thread-safe if the documentation of the corresponding class states that it is not thread-safe.

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.

final class CountHits {
  private static int counter;
  
  public void incrementCounter() {
    counter++;
  }
}

It relies on clients to externally synchronize the object and states its 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.

final 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 classes' 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

[[API 06]]
[[Bloch 08]] Item 67: "Avoid excessive synchronization"


VOID CON06-J. Do not defer a thread that is holding a lock      11. Concurrency (CON)      

  • No labels