Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
public void doSomething(File file) {
  final Lock lock = new ReentrantLock();
  try {
    lock.lock();
    //InputStream Doin something= withnew the protected resourceFileInputStream( file);
    // ThisDo maysomething causewith anthe exception such as FileNotFoundExceptionopen file.
    lock.unlock();
  } catch(FileNotFoundException fnf) {
    // Handle the exception
  }
}

...

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 when the finally clause executes.

Code Block
bgColor#ccccff
public void doSomething(File file) {
  final Lock lock = new ReentrantLock();
  lock.lock();
  try {
    //InputStream Doin something= withnew the protected resourceFileInputStream( file);
    // ThisDo maysomething causewith anthe exception such as FileNotFoundExceptionopen file.
  } catch(FileNotFoundException fnf) {
    // Handle the exception
  } finally {
    lock.unlock();
  }
}

...

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

  public void doSomething(String str) {
    try {lock.lock();
      lock.lock();try {
      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 Intrinsic locks are associated with the use of the synchronized keyword, and are automatically released on exceptional conditions such as abnormal thread termination.

...