Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added NCE/CS to cover runtime exceptions

...

This means that an unreleased lock in any thread will stop other threads from acquiring the same lock.

Noncompliant Code Example (checked exception)

This noncompliant code example protects a resource by using a ReentrantLock but on an exceptional condition, fails to release the lock. Control flow transfers to the catch block and the call to unlock() does not execute.

...

Code Block
bgColor#ccccff
public void doSomething() {
  final Lock lock = new ReentrantLock();
  lock.lock();
  try {
    // Do something with the protected resource
    // This may cause an exception such as FileNotFoundException
  } catch(FileNotFoundException fnf) {
    // Handle the exception
  } finally {
    lock.unlock();
  }
}

Noncompliant Code Example (unchecked exception)

This noncompliant code example protects the thread-unsafe Date instance using a ReentrantLock. It also needs to catch Throwable to be compliant with EXC06-J. Do not allow exceptions to transmit sensitive information.

Code Block
bgColor#FFcccc

class DateHandler {
  private Date date = new Date();
  final Lock lock = new ReentrantLock();

  public void doSomething(String str) {
    try {
      lock.lock();
      String dateString = date.toString();
      if (dateString.equals(str)) {
        // ...
      }
      lock.unlock();
    } catch(Throwable t) {
      // Forward to handler
    }
  }
}

However, because it does not check whether str is null , a runtime exception in this component may prevent the lock from being released.

Compliant Solution

This compliant solution adds a finally block and moves the unlock() call to it.

Code Block
bgColor#ccccff

class DateHandler {
  private Date date = new Date();
  final Lock lock = new ReentrantLock();

  public void doSomething(String str) {
    try {
      lock.lock();
      String dateString = date.toString();
      if (str.equals(dateString)) {
        // ...
      }
    } catch(Throwable t) {
      // Forward to handler
    } finally {
      lock.unlock();
    }
  }
}

Consequently, the lock is released successfully even in the event of a runtime exception.

Compliant Solution

Exceptions

EX1 : Locks associated with the use of the synchronized keyword are automatically released on exceptional conditions such as abnormal thread termination.

...