This discussion is archived
1 Reply Latest reply: Feb 22, 2007 1:17 PM by 796447 RSS

DeadLock

807599 Newbie
Currently Being Moderated
Hi, Here is an example for Deadlock for Sun site

example:
public class Deadlock {
    static class Friend {
        private final String name;
        public Friend(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public synchronized void bow(Friend bower) {
            System.out.format("%s: %s has bowed to me!%n", 
                    this.name, bower.getName());
            bower.bowBack(this);
        }
        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s has bowed back to me!%n",
                    this.name, bower.getName());
        }
    }

    public static void main(String[] args) {
        final Friend alphonse = new Friend("Alphonse");
        final Friend gaston = new Friend("Gaston");
        new Thread(new Runnable() {
            public void run() { alphonse.bow(gaston); }
        }).start();
        new Thread(new Runnable() {
            public void run() { gaston.bow(alphonse); }
        }).start();
    }
}
Description:

When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack. Neither block will ever end, because each thread is waiting for the other to exit bow.


But I have couple of questions:

1) Here we see 2 instances of class Friend - alphonse & gaston. He created 2 instances of Thread class.For the first thread, he created an instance of Thread with run() method and called alphonse.bow(gaston) object to start. My question is since the method bow is synchronized, first thread calls the bow method and processes what ever it does and once the thread is released, now the second thread will call the bow() method. Since we are using synchronized methods, no 2 threads can be processed at a time. The second thread can process only once the first thread releases the resources. Then how deadlock occurs here.

Am I analysing in a right way.

Please correct me if I m wrong.

Thanks
  • 1. Re: DeadLock
    796447 Newbie
    Currently Being Moderated
    The methods are synchronized against threads using the same object. You have two objects here, not just one. So when thread 1 invokes the method on instance 1 (or alphonse), that has no effect on thread 2 invoking the same method on instance 2 (or gaston).