Java中的AutoLock - 如何?

时间:2008-09-30 05:58:23

标签: java synchronization locking

离开作用域时,释放资源的最佳方法是什么(在这种情况下解锁ReadWriteLock)?如何涵盖所有可能的方式(退货,休息,例外等)?

3 个答案:

答案 0 :(得分:11)

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();
}

答案 1 :(得分:2)

像迈克说的那样,最后一块应该是你的选择。请参阅finally block tutorial,其中说明了:

  

finally块始终执行时   try块退出。这确保了   即使是,也执行finally块   发生意外的异常。

答案 2 :(得分:0)

更好的方法是使用try-with-resources语句,它可以让你模仿C ++的RAII mechanism

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

    }

}