Java中的自动锁定-如何?

时间:2020-03-06 14:54:32  来源:igfitidea点击:

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

解决方案

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

就像迈克说的那样,finally块应该是选择。请参阅finally块教程,其中指出:

The finally block always executes when
  the try block exits. This ensures that
  the finally block is executed even if
  an unexpected exception occurs.