Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tweaked 2nd NCCE, stronger

...

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

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

  public // ...
  void doSomething(String str) {
    }
lock.lock();
    String dateString = lockdate.unlocktoString();
    } catch(Throwable tif (dateString.equals(str)) {
      // ...
  Forward to handler}
    }lock.unlock();
  }
}

However, because it 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 block clause and moves the unlock() call to into it.

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

  public void doSomethingdoSomethingSafely(String str) {
    try {
      lock.lockdoSomething(str);
    } catch(Throwable tryt) {
      String// dateStringForward = date.toString();
      if (str.equals(dateString)to handler
    }
  }

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

...