Versions Compared

Key

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

...

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. This problem is hard to notice because threads that accept instances of SynchronizedBase also freely accept instances of its subclasses. Consequently, the threads may incorrectly assume that the subclasses are thread-safe.

Code Block
bgColor#FFCCCC
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.

...

EX1: If the subclass implements block synchronization instead of method synchronization, it is quite possible likely that thread-safety has been accounted for. This condition should be sufficiently documented.

...