Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips to prevent deadlocks in java

I am studying java threads and deadlocks, I understand deadlock's examples but I wonder if there are general rules to follow to prevent it.

My question is if there are rules or tips that can be applied to the source code in java to prevent deadlocks? If yes, could you explain how to implement it?

like image 333
iberck Avatar asked May 27 '13 21:05

iberck


People also ask

How do you prevent deadlocks in threads?

The canonical technique for deadlock avoidance is to have a lock hierarchy. Make sure that all threads acquire locks or other resources in the same order. This avoids the deadlock scenario where thread 1 hold lock A and needs lock B while thread 2 holds lock B and needs lock A.

What causes deadlock in Java?

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

Some quick tips out of my head

  • don't use multiple threads (like Swing does, for example, by mandating that everything is done in the EDT)
  • don't hold several locks at once. If you do, always acquire the locks in the same order
  • don't execute foreign code while holding a lock
  • use interruptible locks
like image 164
JB Nizet Avatar answered Sep 20 '22 17:09

JB Nizet