Tips to prevent deadlocks in java
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.
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