I\'m learning about deadlocks in Java, and there\'s this sample code from Sun\'s official tutorial:
Alphonse and Gaston are friends, and great belie
One important point to note is that it is not methods which are locked but object instances.
When you call alphonse.bow(gaston)
, it tries to acquire the lock on alphonse
. Once it has the lock, it prints a message, then calls gaston.bowBack(alphonse)
. At this point, it tries to acquire the lock on gaston
. Once it has the lock, it prints a message, then releases the lock, and finally the lock on alphonse
is released.
In deadlock, the locks are acquired in such an order that there's no way for either thread to proceed.
alphonse
gaston
gaston
- can't, because Thread 2 already has it.alphonse
- can't, because Thread 1 already has it.