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
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.
ConcurrentLinkedQueue
instead of a synchronized ArrayList
) 上一篇: 什么情况下需要在Java中同步方法访问?
下一篇: 提示,以防止java中的死锁