Versions Compared

Key

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

...

Code Block
bgColor#ccccff
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 preferable preferred choice when untrusted code can obtain the intrinsic lock of the class object (CON04-J. Use the private lock object idiom instead of intrinsic synchronization).

Code Block
bgColor#ccccff

// ...
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.

...