Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 provides an implementation that is not safe for concurrent use.

The guideline CON04-J. Synchronize Use private final lock objects to synchronize classes that may interact with untrusted code using a private final lock object recommends documenting the locking strategy of classes designed for inheritance. This information is useful for deciding the locking strategy of subclasses.

...

This compliant solution does not violate CON04-J. Synchronize Use private final lock objects to synchronize classes that may interact with untrusted code using a private final lock object because the accessibility of the class is package-private which is allowable when untrusted code cannot infiltrate the package.

...

This noncompliant code example defines a doSomething() method in class Base that uses a private final lock, in accordance with CON04-J. Synchronize Use private final lock objects to synchronize classes that may interact with untrusted code using a private final lock object.

Code Block
bgColor#FFCCCC
class Base {
  private final Object lock = new Object();

  public void doSomething() {
    synchronized (lock) {
      // ...	
    }
  }
}

class Derived extends Base {
  public void doSomething() {
    try {
      super.doSomething();
    } finally {
      logger.log(Level.FINE, "Did something"); 
    }
  }
}

...