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.
The Fortify documentation describes the unreleased resource bug as:
The program can potentially fail to release a system resource.
That's not true for your example. If tryLock returns false or throws an exception, no lock was acquired, the try block isn't entered, and there's nothing to release (so no finally block required in the outer try-block). If tryLock returns true, the inner try block is entered and the lock is released in the finally.
What you have seems identical to how the API documentation recommends you do this:
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
The only difference is your example uses the override of tryLock that times out, in which case it returns false. So from what's posted this seems ok.