Лучший способ сделать это - использовать оператор try-with-resources, который позволяет имитировать механизм C ++ RAII :
public class MutexTests {
static class Autolock implements AutoCloseable {
Autolock(ReentrantLock lock) {
this.mLock = lock;
mLock.lock();
}
@Override
public void close() {
mLock.unlock();
}
private final ReentrantLock mLock;
}
public static void main(String[] args) throws InterruptedException {
final ReentrantLock lock = new ReentrantLock();
try (Autolock alock = new Autolock(lock)) {
// Whatever you need to do while you own the lock
}
// Here, you have already released the lock, regardless of exceptions
}
}