Question about deadlock from Sun tutorials

Below is the code directly from Sun's tutorials describing Deadlock. However, I do not understand how Deadlock can occur in this situation if both methods are synchronized. How would two threads be inside the same synchronized methods at the same time?

The deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here is an example.

Alphonse and Gaston are friends and great believers in politeness. The strict rule of courtesy is that when you bow to a friend, you must remain worshiped until your friend can return the bow. Unfortunately, this rule does not take into account the possibility that two friends can worship each other at the same time. This sample Deadlock application allows you to use this feature:

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(); } } 

When Deadlock fires, it is very likely that both threads will block when trying to call bowBack. None of the blocks will ever end, because each thread is waiting for the other to exit the bow.

+6
java
source share
1 answer

Synchronized (instances) methods block an object, not a class.

alphonse.bow captures the alphabetical lock, and gaston.bow captures the gadon lock. When the “alphonse” stream is in the bow, it tries to grab the lock on the “gadon” on bower.bowBack. Likewise, the crap tries to capture an alpha lock.

Edit for clarity (hopefully):

Let the two threads Thread1 and Thread2 be called.

Thread1 launches alphonse.bow (gaston), where it grabs a lock on the alpha object, and Thread2 launches gaston.bow (alphonse) and grabs a lock on the gastant object.

In Thread1, when he tries to run bower.bowBack (this), where bower = gaston, the thread must first get a lock on the gadon.

While this continues, Thread2 is trying to do the same, with bower = alphonse. Thread1 has the lock that Thread2 requires, and vice versa, so a deadlock occurs.

As an aside, a dead end does not have to arise. If Thread1 can start and end before Thread2 has the ability to do this (for example, if something hangs in the main thread after Thread1 starts, but before Thread2 is created / started), then there will be a deadlock.

+7
source share

All Articles