Deadlock detection in Java

2020-01-25 13:19发布

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 Edition, p.516)

So, what is about it? Is there a way to catch deadlock case in Java? I mean, is there a way that our code understands a deadlock case occurred?

15条回答
做个烂人
2楼-- · 2020-01-25 13:47

If you are running from the command-line and you suspect that you are deadlocked, try ctrl+break in windows (ctrl+\ in unix) to get a thread dump. See http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/gbmps.html

查看更多
孤傲高冷的网名
3楼-- · 2020-01-25 13:53

Java can detect deadlocks (although not at run-time, it can still diagnose and report it).

For example, when using a slightly modified version of 'Saurabh M. Chande' code bellow (changed it to Java and added some timing to guarantee a lock on each run). Once you run it and it deadlocks, if you type:

kill -3 PID   # where 'PID' is the Linux process ID

It will generate a stack dump, which will include the following information:

Found one Java-level deadlock:
=============================
"Thread-0":
     waiting to lock monitor 0x08081670 (object 0x7f61ddb8, a Deadlock$A),
     which is held by "main"
"main":
      waiting to lock monitor 0x080809f0 (object 0x7f61f3b0, a Deadlock$B),
      which is held by "Thread-0"
查看更多
做自己的国王
4楼-- · 2020-01-25 13:56

Not exactly what you asked, but when a deadlock does occur, you can do a "kill -3" on the process id and it dumps a thread dump to stdout. Also, the 1.6 jvm has some tools to do the same thing in a gui manner.

查看更多
Deceive 欺骗
5楼-- · 2020-01-25 13:57

Java 5 introduced ThreadMXBean - an interface that provides various monitoring methods for threads. ... The difference is that findDeadlockedThreads can also detect deadlocks caused by owner locks (java.util.concurrent), while findMonitorDeadlockedThreads can only detect monitor locks (i.e. synchronized blocks)

Or you can detect it programatically, refer this https://dzone.com/articles/how-detect-java-deadlocks

查看更多
倾城 Initia
6楼-- · 2020-01-25 13:58

Dr. Heinz Kabutz of JavaSpecialists has written an entertaining and informative newsletter issue on Java deadlocks and describes something called a ThreadMXBean in another newsletter issue. Between those, you should get a good idea of the issues and some pointers to doing your own instrumentation.

查看更多
家丑人穷心不美
7楼-- · 2020-01-25 13:58

If you're debugging in eclipse, you can pause the application (select the app in the debug view and the little || button on the debug toolbar) and then it can report deadlocks.

See http://runnerwhocodes.blogspot.com/2007/10/deadlock-detection-with-eclipse.html for an example.

查看更多
登录 后发表回答