5

I'm trying to write very simple program which will imitate simple DeadLock, where Thread A waits for Resource A locked by Thread B and Thread B waits for Resource B locked by Thread A.

Here is my code:

//it will be my Shared resource
public class Account {
    private float amount;

    public void debit(double amount){
        this.amount-=amount;
    }

    public void credit(double amount){
        this.amount+=amount;
    }

}  

This is my runnable which performs Operation on the resource above:

public class BankTransaction implements Runnable {
    Account fromAccount,toAccount;
    float ammount;
    public BankTransaction(Account fromAccount, Account toAccount,float ammount){
        this.fromAccount = fromAccount;
        this.toAccount = toAccount;
        this.ammount = ammount;
    }

    private void transferMoney(){
        synchronized(fromAccount){
            synchronized(toAccount){
                fromAccount.debit(ammount);
                toAccount.credit(ammount);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                e.printStackTrace();
                }
                System.out.println("Current Transaction Completed!!!");
            }
        }
    }

    @Override
    public void run() {
        transferMoney();
    }

}

and finally my main class:

    public static void main(String[] args) {

    Account a = new Account();
    Account b = new Account();
    Thread thread1 = new Thread(new BankTransaction(a,b,500));

    Thread thread2 = new Thread(new BankTransaction(b,a,500));
       thread1.start();  
       thread2.start();  
System.out.println("Transactions Completed!!!");

    }
}

Why does this code run execute successfully and I don't have and deadLock?

5 Answers 5

10

It's got the potential for deadlock - but both locks are acquired so quickly together that one thread can get both before the other has the chance to acquire its first one.

Put another Thread.sleep(500); call between the two synchronized statements and it does deadlock: both threads will enter "their" outer lock, sleep, then when they wake up they'll both find that their "inner" lock is already acquired.

This is due to the fact that you synchronized statements are anti-symetrical : for one thread, the outer synchronized lock is the inner one for the other thread and the other way around.

2
  • The sleep can introduce non-determinism. You can make it deterministic; see my answer below.
    – Toby
    Aug 26, 2011 at 10:05
  • @Toby: Yes, you can make it deterministic - but sleep is a good way of showing how the deadlock can occur, as you can always imagine a program without sleeps executing similarly to one which does use sleeps, simply by virtue of the thread not being scheduled. In other words, a program which fails when you insert sleeps is inherently flawed because you could see the same "accidentally" in real life. The same isn't true with inserting notifications.
    – Jon Skeet
    Aug 26, 2011 at 10:11
5

It's possible that one of the threads will enter both synchronized sections, blocking the other thread entirely until it's finished.

4

You need to simulate 'unfortunate timing'. Try adding sleep between two locks:

synchronized(fromAccount){
    Thread.sleep(2000);
    synchronized(toAccount){
2

Sleeps as suggested by Jon above can introduce non-determinism, you could make it deterministic using some coordinator like a latch instead. To clarify though, I'm thinking of it as a testing problem: how to prove a deadlock every time and that may not be what you're looking for.

See this code for an example and a blog post describing it a little.

0

The reason of deadlock is that thread A is wait for Thread B to release some resource before A continue; the same to thread B, it wont continue until thread A releases some resource. In other words, A and B wait forever to each other.

In the code snippet, synchronized can block other threads for while because only one thread can execute the block at the moment. thread.sleep() suspend the thread for 500 millisecond, then continue. The wait forever mutually condition doesnt satisfy, that why it is not deadlock.

Following snippet is a good example to illustrate deadlock

public class threadTest{

    public class thread1 implements Runnable{
      private Thread _th2;
      private int _foo;

      public thread1(Thread th2){};
      public void run(){
        for(int i = 0; i<100; i++){foo += foo;};
        synchronized(this){this.notify()};
        synchronized(_th2){
            _th2.wait();
           _foo += _th2.foo;
           System.out.print(" final result " + _foo);
        }
      }
     }

     public class thread2 implements Runnable{
        private final thread1 _th1; private int _foo;
        public thread2(thread1 th1){};
        public void Run(){
           synchronized(_th1){_th1.wait()};
           synchronized(this){
             _foo += th1._foo();
             this.notify();                
           }
        }
     } 
    }
}

//just ignore the way to access private variable in the class

Because there is no mechanism assuring the execution order of two threads, it is very possible thread 2 wont receive the notification from thread1 since it starts lately, thus it waits for the notification before continue execution. Same to thread1, it cant do next execution until it receives notification from thread2. both of them wait for each other forever, typical deadlock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.