java - 当我读Core.Java.Volume.I时,我无法理解这句话的含义

标签 java

当我阅读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() 或采取一些紧急行为来解决此问题。

关于java - 当我读Core.Java.Volume.I时,我无法理解这句话的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40312480/

相关文章:

java - 让 Hibernate 知道隐藏的实体关系

java - 将数字组合成一个 Java 变量

java - 如何使用 Criteria API 进行 JOIN ON 查询

java - com.twitter.sdk.android.core.TwitterApiException : HTTP request failed, 状态:403

java - 如何使用 Java 编辑 docx

java - 键绑定(bind)问题

java - 如何在代号一中将doneListener添加到TextArea

java - 在 swing 线程中捕获异常

java - 无法读取整个文件,仅读取一行

java - 验证/验证 Google Play 游戏服务 ID?