How To Avoid Deadlock In java
How to avoid deadlocks
One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time, which is often practical. However, if you have to acquire more then one lock for some purpose then acquire multiple locks in a consistent, defined order.
Depending on how your program uses locks, it might not be complicated to ensure that you use a consistent locking order. You can define a lock acquisition ordering on the set of locks and ensure that you always acquire locks in that order. Once the lock order is defined, it simply needs to be well documented to encourage consistent use throughout the program.
Following are the zest about how we can avoid deadlock in the context of java,
One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time, which is often practical. However, if you have to acquire more then one lock for some purpose then acquire multiple locks in a consistent, defined order.
Depending on how your program uses locks, it might not be complicated to ensure that you use a consistent locking order. You can define a lock acquisition ordering on the set of locks and ensure that you always acquire locks in that order. Once the lock order is defined, it simply needs to be well documented to encourage consistent use throughout the program.
Following are the zest about how we can avoid deadlock in the context of java,
- Narrow down the synchronization's scope to as small a block as possible.
- Try to avoid locking multiple objects if possible.
- Use a consistent lock order, by which if multiple locks need to be acquired will be acquired in a particular predefined order.
- Maintain a proper documentation about the order , and other locking strategy if used.
More details discussion with Example hands on would be posted in my on Deadlocks.
Nice and simple explanation , I like this. here is another good explanation on cause and solution of deadlock in java
ReplyDeleteThread Deadlock can be avoided by using interthread communication. Interthread communication can be acheieved by following 3 methods:
ReplyDelete1. wait()
2. notify()
3. notifyall()
When a thread executes wait() method, the thread releases the lock and enters into wait pool, until it gets notification from other thread. Whenever other notifies the thread in wait pool resumes the action.
notify() method notifies only one thread at a time.
notifyall() method notifies all the threads in wait pool.
Based on JVM implementation, one method resumes at a time.
wait(), notify() and notifyall() methods should be used inside synchronized block.