0

The example illustrates how deadlock happens. There is one thing I don't understand, which is that when the first thead that calls method bow of instance alphone is about to execute gaston.bowbBack (this), does the thread will release lock and acquire the lock of the instance gaston if, suppose, it is not owned by the second thread? or will it hold two locks at the same time utill all the code of the method is executed completely? And another question, is there any way to check whether a thread is holding a lock?

  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();
        }
    }
PMH
  • 85
  • 1
  • 7
  • ok anytime i see this example crop up i start looking to close this as a duplicate, we've been over this one a lot. and yes, no reason a thread can't hold more than 1 lock at once. the selected answer on the linked post should spell out what happens. – Nathan Hughes Dec 04 '14 at 14:47

2 Answers2

2

1) a thread can have more than one lock, like this

    ...
    synchronized (obj1) {
        System.out.println(1);
        synchronized (obj2) {
            System.out.println(2);
        }
    }
    ...

2) we can check if a thread is holding a lock with Thread.holdsLock(Object obj)

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

A thread will not release a lock by virtue of acquiring another one; it can hold multiple locks. Re: your second question, yes there is a way to see if the current thread holds the monitor lock of an object (Thread#holdsLock)

Enno Shioji
  • 26,542
  • 13
  • 70
  • 109