当我阅读Core.Java.Volume.I时,我无法理解这句话的含义:
"Be careful to ensure that the code in a critical section is not bypassed by throwing an exception. If an exception is thrown before the end of the section,the finally clause will relinquish the lock, but the object may be in a damaged state."
我怎样才能确保这一点?抛出异常时不是必须绕过临界区的代码吗?
考虑这个伪代码:
Patient patient = service.getPatient(name);
hospitalEquipment.lock();
try {
patient.pauseLifeSupport();
// some code causing an exception
patient.resumeLifeSupport();
} finally {
hospitalEquipment.unlock();
}
在此伪代码中,异常导致“关键部分”被绕过,即恢复生命支持。您可以通过将调用移至 finally
block 内的 resumeLifeSupport()
或采取一些紧急行为来解决此问题。
我是一名优秀的程序员,十分优秀!