Concurrency related vulnerabilities can manifest themselves when assumptions are made about the multithreaded behavior of derived classes. An overridden synchronized method's contract may be violated if a subclass defines an implementation that is not thread safe.
Noncompliant Code Example
This noncompliant code example defines a synchronized doSomething() method in a class called SynchronizedBase. The method can be safely used by many threads. However, if a subclass UnsynchronizedSubclass overrides the method but leaves it unsynchronized, its instance cannot be safely passed to multiple threads.
public class SynchronizedBase {
public synchronized void doSomething() {
// ...
}
}
public class UnsynchronizedSubclass extends SynchronizedBase {
public void doSomething() {
// ...
}
}
This problem is hard to notice because threads that accept instances of SynchronizedBase also accept instances of its subclasses. Consequently, the threads may incorrectly assume that the subclasses are thread-safe.
Compliant Solution
This compliant solution synchronizes the doSomething() method of the subclass.
public class SynchronizedBase {
public synchronized void doSomething() {
// ...
}
}
public class SynchronizedSubclass extends SynchronizedBase {
public synchronized void doSomething() {
// ...
}
}
Compliant Solution
An alternative is to use block synchronization by defining an internal private final lock object in the extending class. This is the preferred choice when untrusted code can obtain the intrinsic lock of the class object (CON04-J. Use the private lock object idiom instead of the object's intrinsic locking mechanism).
// ...
public class SynchronizedSubclass extends SynchronizedBase {
private final Object lock = new Object();
public void doSomething() {
synchronized(lock) {
// ...
}
}
}
Exceptions
EX1: If the subclass implements block synchronization instead of method synchronization, it is likely that thread-safety has been accounted for. This condition should be sufficiently documented.
Risk Assessment
Failure to provide synchronization in overriding methods can result in unexpected behavior.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
CON10- 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]]
[[SDN 08]] Sun bug database, Bug ID 4294756![]()
CON09-J. Do not invoke alien methods that rely on invariants protected by the same lock object 11. Concurrency (CON) CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members