Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: removed a line because it was suggesting a solution in the NCE; also interhanged str and dateString so that a null ptr exception actually results

...

Code Block
bgColor#FFcccc
class DateHandler {
  private 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 (dateStringstr.equals(strdateString)) {
      // ...
    }
    lock.unlock();
  }
}

However, because the doSomething() method does not check whether str is null , a runtime exception in this component may prevent the lock from being released.It is important that releasing dynamic locks always be executed within an finally clause in order to work correctly with unexpected or unchecked exceptions.

Compliant Solution

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

Code Block
bgColor#ccccff
class DateHandler {
  private 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 (dateStringstr.equals(strdateString)) {
        // ...
      }
    } finally {
      lock.unlock();
    }
  }
}

...