Search code examples
javaconcurrencydeadlocksynchronized

I don't understand why this code is causing a deadlock


I'm following the oracle documentation about concurrency, and in the deadlock section they use the below example. The problem is that I don't quite understand why is this causing a deadlock.

As I see it, that's what I guess it's happening:

  • Alphonse bows Gaston and acquires the lock on the bow method
  • Alphonse leaves the bow method and goes into bowBack, releasing the first lock and acquiring the second one.
  • Gaston repeats the process

But I must be wrong, because if you run the code, it causes a deadlock... what am I missing here?

Thanks a lot!

public class Deadlock
{
    public static void main(String[] args)
    {
        final Friend alphonse = new Friend("Alphonse");
        final Friend gaston = new Friend("Gaston");

        new Thread(() -> alphonse.bow(gaston)).start();
        new Thread(() -> gaston.bow(alphonse)).start();
    }


    static class Friend
    {
        private final String name;


        Friend(final String name)
        {
            this.name = name;
        }


        String getName()
        {
            return name;
        }


        synchronized void bow(final Friend bower)
        {
            System.out.printf("%s: %s has bowed to me!%n", this.name, bower.getName());
            bower.bowBack(this);
        }


        synchronized void bowBack(final Friend bower)
        {
            System.out.printf("%s: %s has bowed back to me!%n", this.name, bower.getName());
        }
    }
}

Solution

  • Say both threads are in bow on the System.out.printf line. When they try to call bowBack, they will both need to acquire a lock on the other instance before bow can return and release the locks.

    Since both threads are locked, waiting for one another to unlock, this is a deadlock.