Deadlock detection in Java

后端 未结 16 1053
野的像风
野的像风 2020-11-28 20:21

Long time ago, I saved a sentence from a Java reference book: \"Java has no mechanism to handle deadlock. it won\'t even know deadlock occurred.\" (Head First Java 2nd E

16条回答
  •  隐瞒了意图╮
    2020-11-28 21:03

    Deadlocks can be avoided if you follow a simple rule: have all threads claim and release their locks in the same order. In this way, you never get into a situation where a deadlock can occur.

    Even the dining philosophers problem can be seen as a violation of this rule as it uses relative concepts of left and right spoon which result in different threads using different allocation orders of the spoons. If the spoons were numbered uniquely and the philosophers all tried to get the lowest numbered spoon first, deadlock would be impossible.

    In my opinion, prevention is better than cure.

    This is one of the two guidelines I like to follow to ensure threads work properly. The other is ensuring each thread is solely responsible for its own execution as it's the only one fully aware of what it's doing at any point in time.

    So that means no Thread.stop calls, use a global flag (or message queue or something like that) to tell another thread you want action taken. Then let that thread do the actual work.

提交回复
热议问题