Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: edits

...

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

...

This compliant solution uses a try-finally block immediately after acquiring the lock. This ensures that the lock is appropriately released even in the event of an exceptional condition. Also the lock is acquired outside the try block, which guarantees that the lock is actually obtained held when the finally clause executes.

...

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
final class DateHandler {
  private final Date date = new Date();
  final Lock lock = new ReentrantLock();

  public void doSomethingSafely(String str) {
    try {
      doSomething(str);
    } catch(Throwable t) {
      // Forward to handler
    }
  }

  public void doSomething(String str) {
    lock.lock();
    String dateString = date.toString();
    if (str.equals(dateString)) {
      // ...
    }
    lock.unlock();
  }
}

...

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

Code Block
bgColor#ccccff
final class DateHandler {
  private final Date date = new Date();
  final Lock lock = new ReentrantLock();

  public void doSomethingSafely(String str) {
    try {
      doSomething(str);
    } catch(Throwable t) {
      // Forward to handler
    }
  }

  public void doSomething(String str) {
    try {
      lock.lock();
      String dateString = date.toString();
      if (str.equals(dateString)) {
        // ...
      }
    } finally {
      lock.unlock();
    }
  }
}

...