2

离开作用域时释放资源(在这种情况下解锁 ReadWriteLock)的最佳方法是什么?如何涵盖所有可能的方式(返回、中断、异常等)?

4

3 回答 3

12

try/finally 块是最接近这种行为的方法:

Lock l = new Lock();
l.lock();  // Call the lock before calling try.
try {
    // Do some processing.
    // All code must go in here including break, return etc.
    return something;
} finally {
    l.unlock();
}
于 2008-09-30T06:05:11.287 回答
2

就像迈克所说,一个 finally 块应该是你的选择。请参阅finally 块教程,其中说明:

finally 块总是在 try 块退出时执行。这样可以确保即使发生意外异常也会执行 finally 块。

于 2008-09-30T06:20:14.540 回答
1

一个更好的方法是使用 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

    }

}
于 2017-11-27T13:33:29.830 回答