tryLock unreleased resource

Viewed 428

The code below has been flagged as a violation by Fortify ("unreleased resource" for the lock)

try {
  if (lock.tryLock(1, TimeUnit.SECONDS)) {
    try {
      //do something
    }
    finally {
       lock.unlock();
   }
}
catch (InterruptedException e) {
  // something
}

Could you please explain why? Should there be a finally statement for the InterruptedException try/catch? I thought that the inner try would handle this case as well.

2 Answers

I might have a decent solution:

long timeout = ...;
Lock someLock = ...;
try {
    if (!someLock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
        // TODO: print some error;
        return;
    }
} catch (InterruptedException e) {
    // TODO: print some error;
    return;
}

try{
    // TODO: Some Logic
} finally {
    someLock.unlock();
}
Related