Tips to prevent deadlocks in java Tips to prevent deadlocks in java multithreading multithreading

Tips to prevent deadlocks in java


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.


  1. Avoid locks by using lock-free data structures (e.g. use a ConcurrentLinkedQueue instead of a synchronized ArrayList)
  2. Always acquire the locks in the same order, e.g. assign a unique numerical value to each lock and acquire the locks with lower numerical value before acquiring the locks with higher numerical value
  3. Release your locks after a timeout period (technically this doesn't prevent deadlocks, it just helps to resolve them after they've occurred)