Reputation: 8682
I have code like this:
public class Thingy {
private final Lock lock = new ReentrantLock();
private boolean shutdown;
public void shutdown() {
lock.lock();
shutdown = true;
lock.unlock();
}
}
And FindBugs complains that "Thingy.shutdown() does not release lock on all exception paths" and that I should wrap the shutdown = true;
line in a try-finally, but as far as I can see there is no way that this can go bad.
Am I wrong or is this a false-positive?
Upvotes: 4
Views: 1941
Reputation: 4706
Its true, but so is the fact that using a lock here is the wrong thing. You only need volatile
.
In fact you don't even need that as you never read the value, so you can elide the variable and the lock altogether.
Point being that for a simple write, findbugs warning something is probably correct, it just is warning the wrong thing.
Upvotes: 2
Reputation: 18998
To be fair, it's generally fairly tricky (without being a full-on compiler and doing the analysis) to determine whether any given piece of code can throw an exception or not.
But I agree, in this case, it's a false positive. And even if it isn't - even if there's some dark corner of the JLS/JVM spec that says an assignment can, somehow, through an exception - if you get into that state, you've got more to worry about than an un-released lock!
Upvotes: 5