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?


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

  • Encapsulate, encapsulate, encapsulate! Probably the most dangerous mistake you can make with locks is exposing your lock to the world (making it public). There is no telling what can happen if you do this as anyone would be able to acquire the lock without the object knowing (this is also why you shouldn't lock this ). If you keep your lock private then you have complete control and this makes it more manageable.


  • Avoid locks by using lock-free data structures (eg use a ConcurrentLinkedQueue instead of a synchronized ArrayList )
  • Always acquire the locks in the same order, eg assign a unique numerical value to each lock and acquire the locks with lower numerical value before acquiring the locks with higher numerical value
  • Release your locks after a timeout period (technically this doesn't prevent deadlocks, it just helps to resolve them after they've occurred)
  • 链接地址: http://www.djcxy.com/p/76266.html

    上一篇: 什么情况下需要在Java中同步方法访问?

    下一篇: 提示,以防止java中的死锁