Concurrency related issues 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 provides an implementation that is not safe for concurrent use.
...
This noncompliant code example defines a doSomething() method in class Base that uses an internal a private final lock, in accordance with CON04-J. Synchronize classes that may interact with untrusted code using a private final lock object.
...
The doSomething() method of class Derived cannot be safely used by multiple threads because it is not thread-safe. It is possible that multiple threads may cause the entries to be logged in an order different than the one that differs from the order in which the tasks are performed.
...
This compliant solution synchronizes the doSomething() method of the subclass using a private final lock object.
| Code Block | ||
|---|---|---|
| ||
class Base {
private final Object lock = new Object();
public void doSomething() {
synchronized (lock) {
// ...
}
}
}
class Derived extends Base {
private final Object lock = new Object();
public void doSomething() {
synchronized (lock) {
try {
super.doSomething();
} finally {
logger.log(Level.FINE, "Did something");
}
}
}
}
|
...