Friday, 12 April 2013

A sample program to fix a Deadlock



For avoiding deadlock we need to provide an ordered access of resources to threads.



package com.gaurav.multithreads;

/**
 * Here I am demonstration of how to write multithreaded programs, which will not result a *deadlock.
* To avoid this sort of deadlock when locking multiple resources, all threads
 * should always acquire their locks in the same order.
 **/
public class FixingTheDeadlock {
 
    public static void main(String[] args) {
   
        /** These are the two resource objects we'll try to get locks for */
    final Object FIRST_RESOURCE = "first_resource";
    final Object SECOND_RESOURCE = "second_resource";
   
    /** Here's the first thread.  It tries to lock FIRST_RESOURCE then SECOND_RESOURCE */
    Thread t1 = new Thread() {
      public void run() {
       
          /** Lock FIRST_RESOURCE */
        synchronized(FIRST_RESOURCE) {
          System.out.println("Thread 1: locked FIRST_RESOURCE");

          /** Pause for a moment. 
           Here we are giving a chance to the other thread to
           run. */
          try {
              Thread.sleep(100);
              }
          catch (InterruptedException ie) {
              System.out.println(ie.getMessage());
          }
         
          /** Now wait till we can get a lock on SECOND_RESOURCE */
          synchronized(SECOND_RESOURCE) {
            System.out.println("Thread 1: locked SECOND_RESOURCE");
          }
        }
      }
    };
   
    /** Here's the second thread.  It tries to lock FIRST_RESOURCE at first and then SECOND_RESOURCE
     * in same order followed by first Thread*/
   
    Thread t2 = new Thread() {
      public void run() {
       
          /** This thread locks FIRST_RESOURCE now */
        synchronized(FIRST_RESOURCE) {
          System.out.println("Thread 2: locked FIRST_RESOURCE");

          /** Then it pauses  for the same reason as the first thread does */
          try {
              Thread.sleep(100);
              }
          catch (InterruptedException ie) {
              System.out.println(ie.getMessage());
          }

            synchronized(SECOND_RESOURCE) {
            System.out.println("Thread 2: locked SECOND_RESOURCE");
          }
        }
      }
    };
   
    /** Start both the threads. Now, deadlock will not occur, and the program will exit after execution. */
    t1.start();
    t2.start();
  }
}


Note :- Now there would not be any deadlock because both threads is accessing lock on FIRST_RESOURCE and then SECOND_RESOURCE object in same order .
So if thread t1 acquires lock on FIRST_RESOURCE object , thread t2 will not proceed until thread t1 releases FIRST_RESOURCE lock ,
same way thread t1 will not be blocked even if thread t2 holds SECOND_RESOURCE lock because now thread t2 will not expect thread t1 to release FIRST_RESOURCE lock to proceed for execution.

No comments:

Post a Comment