为什么在JVM检测到死锁时不通过运行时异常来防止死锁?

huangapple 未分类评论40阅读模式
英文:

Why deadlock is not prevented upon detection with a runtime exception by the JVM?

问题

Java可以检测即将发生的死锁(至少在某些情况下)

例如,考虑以下情况:

线程A获取锁A
线程B获取锁B
线程A试图获取锁B - 并被阻塞
线程B试图获取锁A - 并无限期阻塞

在最后一种情况下,Java虚拟机知道它将陷入死锁(因为它知道哪个线程持有哪个锁)。

因此,我的问题是,为什么Java虚拟机在即将导致死锁的锁获取时不会抛出运行时错误,从而终止线程(就像任何其他未处理的异常一样),并释放它的锁,就像正常情况下一样。

例如,在数据库中,如果事务尝试锁定某个记录,并且数据库确定将发生死锁,那么该事务将被中止。
同样的原则也可以应用于线程,那么为什么不呢?

英文:

Java can detect a deadlock that is about to happen (or at least in some cases)

For example, consider the following:

Thread A acquires Lock A
Thread B acquires Lock B
Thread A tries to acquire Lock B - and blocks
Thread B tries to acquire Lock A - and blocks indefinitely

In the last statement, the JVM knows that it will end up in a deadlock (because it knows which thread holds which lock).

So my question is, why the JVM doesn't throw a runtime error upon the lock acquisition that will cause a deadlock, resulting in termination of the thread (like any other unhandled exception), and releasing its locks, again, like normal.

For example, in a database, if a transaction tries to lock some record and the DB figures out it will be deadlocked, that transaction is aborted.
The same can be applied to threads, so why not?

huangapple
  • 本文由 发表于 2020年7月25日 05:36:52
  • 转载请务必保留本文链接:https://java.coder-hub.com/63081790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定