Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deadlock detection in Java

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?

like image 768
israkir Avatar asked Oct 19 '08 22:10

israkir


People also ask

How do you detect deadlock?

The OS can detect the deadlocks with the help of Resource allocation graph. In single instanced resource types, if a cycle is being formed in the system then there will definitely be a deadlock. On the other hand, in multiple instanced resource type graph, detecting a cycle is not just enough.

What tools can detect deadlocks?

JConsole is able to detect deadlocks in a running application.

How do we handle deadlock in Java?

We can avoid Deadlock situation in the following ways: Using Thread. join() Method: We can get a deadlock if two threads are waiting for each other to finish indefinitely using thread join. Then our thread has to wait for another thread to finish, it is always best to use Thread.

What is deadlock in Java with example?

Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other. This usually happens when multiple threads need the same locks but obtain them in different orders. Multithreaded Programming in Java suffers from the deadlock situation because of the synchronized keyword.


1 Answers

Since JDK 1.5 there are very useful methods in the java.lang.management package to find and inspect deadlocks that occurs. See the findMonitorDeadlockedThreads() and findDeadlockedThreads() method of the ThreadMXBean class.

A possible way to use this is to have a separate watchdog thread (or periodic task) that does this.

Sample code:

  ThreadMXBean tmx = ManagementFactory.getThreadMXBean();   long[] ids = tmx.findDeadlockedThreads();   if (ids != null) {      ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);      System.out.println("The following threads are deadlocked:");      for (ThreadInfo ti : infos) {         System.out.println(ti);      }   } 
like image 71
staffan Avatar answered Sep 24 '22 15:09

staffan