从技术角度来看,这两个 list 有何不同?第一个是 lock 的 Java 文档中提供的一个.第二个是我的。
1.
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}
2.
Lock l = ...;
try {
l.lock();
// access the resource protected by this lock
} finally {
l.unlock();
}
最佳答案
原因在the javadoc of the .unlock()
documentation of Lock
中找到:
Implementation Considerations
A Lock implementation will usually impose restrictions on which thread can release a lock (typically only the holder of the lock can release it) and may throw an (unchecked) exception if the restriction is violated. Any restrictions and the exception type must be documented by that Lock implementation.
类似地,.lock()
可能因未经检查的异常而失败。
这意味着:
l.lock();
try {
...
} finally {
l.unlock();
}
如果锁定 失败,您将永远无法unlock()
。而在:
try {
l.lock();
...
} finally {
lock.unlock();
}
如果锁定失败,你不必抛出两个异常;其中一个会丢失。
更不用说根据锁的实现,使用第二个版本你可能最终会解锁“其他人”的锁......这不是一件好事。
关于Java锁定结构最佳模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31058681/