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,


  1. Narrow down the synchronization's scope to as small a block as possible.
  2. Try to avoid locking multiple objects if possible.
  3.  Use a consistent lock order, by which if multiple locks need to be acquired will be acquired in a particular predefined order.
  4. 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.

Comments

  1. Nice and simple explanation , I like this. here is another good explanation on cause and solution of deadlock in java

    ReplyDelete
  2. Thread Deadlock can be avoided by using interthread communication. Interthread communication can be acheieved by following 3 methods:
    1. 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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized