Friday, June 24, 2011

Dead Lock Example

How to create dead lock?  Here is the fine example.
Lets talk about money transfer from one account to another account. Money has to be debited from one account and it has to be credited into another account.


public class Transfer extends Thread
{
           private Credit credit  = null;
           private Debit debit = null;
           private boolean odd = false;

           public Transfer(Credit credit, Debit debit,boolean odd)
           {
                       this.credit=credit;
                       this.debit=debit;
                      this.odd=odd;
            }

            public void run()
            {
                       if(odd)
                      {
                                transferMethod1();
                       }
                       else
                       {
                                 transferMethod2();
                        }
             }

            //first lock credit and then do debit
           public void transferMethod1()
           {
                 credit.credit();
                 //thread.sleep() can be added just to ensure that dead lock is happening
                 debit.debit();
           }

          //first lock debit and then do credit
          public void transferMethod2()
          {
                   debit.debit();
                   //thread.sleep() can be added just to ensure that dead lock is happening  
                  credit.credit();
          }

          public static void main(String a[])
          {
                      Credit c = new Credit();
                      Debit d  = new Debit();
                      Transfer t1 = new Transfer(c,d,true);                     
                      Transfer t2 = new Transfer(c,d,false);
          }
}

class Credit
{
public synchronized credit()
{
//credit implementation
}
}

class Debit
{
public synchronized debit()
{
  //debit implementation
}

When thread t1 calls transferMethod1(), credit object is locked and its waiting for debit object. At the same time, when thread t2 calls transferMethod2(), debit object is locked and its waiting for credit object. t1 can proceed when t2 releases debit object and t2 can proceed when t1 releases credit object. Hence program hangs. One way to avoid this deadlock is, combine those two resources. i.e synchronize both these credit and debit operations. i.e in other words synchronize methods in Transfer object. Make transferMethod1() and transferMethod2() methods synchronized.

No comments:

Post a Comment