3

I have reading concurrency lately on java tutorials in oracle website.Today i read about deadlock/synchronization i am able to understand few things.

Synchronization :

synchronized methods: No two threads can invoke two different synchronized method of same object.Meaning at a given point in time onlyone synchronized methods gets executed per objects even if there are multiple other synch methods .

is my understanding proper.

Deadlock:

In below code deadlock occrus but i am just not able to understand why? why are both threading waiting for each other to get out of bow method ?

package com.tutorial;

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();
    }
}
sumedha
  • 473
  • 1
  • 9
  • 24

1 Answers1

3
  1. alphonse.bow (lock on apohonse)
  2. gaston.bow (lock on gaston)
  3. alphonse.bow calls gaston.bowback (cannot get lock on gaston because in alphonse's thread so is blocked but holding alphonse lock)
  4. gaston.bow calls alphose.bowback (cannot get lock on alphonse because in gaston's thread so is blocked but holding gaston lock)

deadlock

John B
  • 32,493
  • 6
  • 77
  • 98