General information about deadlock, synchronization

Recently I have been reading concurrency in java tutorials on oracle website. I am reading about deadlock / sync today. I can understand a few things.

Synchronization:

synchronized methods: no two threads can call two different synchronized methods of the same object. Execution at a time only one synchronized method is executed per objects, even if there are several other synchronization methods.

is my understanding.

Dead end:

The below code is stuck occrus but I just can't figure out why? why are both threads waiting for each other to exit the 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();
    }
}

      

+3


source to share


1 answer


  • alphonse.bow (lock on apohonse)
  • gaston.bow (gadon lock)
  • alphonse.bow calls gaston.bowback (cannot acquire lock on halo because it is so blocked in the alpha stream, but holds the alpha lock)
  • gaston.bow calls alphose.bowback (cannot get an alphabetical lock because it is so locked in the gastron thread, but holds the gastronomic lock)


deadlocks

+3


source







All Articles