...
The two transfers are performed in their own threads, from instance a
to b
and b
to a
. The first thread atomically transfers the amount from a
to b
by depositing the balance from a
to b
and withdrawing the entire balance from a
. The second thread performs the reverse operation, that is, it transfers the balance from b
to a
and withdraws the balance from b
. When executing depositAllAmount()
, the first thread acquires a lock on object a
while . It is possible for the second thread acquires to acquire a lock on object b
before the first thread can lock b
. Subsequently, the first thread requests would request a lock on b
which is already held by the second thread. The second thread requests would request a lock on a
which is already held by the first thread. This constitutes a deadlock condition, as neither thread can proceed.
This example does not always deadlock, depending on the scheduling details of the platform. Deadlock can occur when two threads request the same two locks in different orders and each thread obtains a lock that prevents the other thread from completeing its transfer. Deadlock might not occur when two threads request the same two locks, but one thread completes its transfer before the other thread begins. Deadlock also cannot occur if the two threads request the same two locks in the same order (which would happen if they both transfer money from one account to a second account), or if two simultaneous transfers occur involving distinct accounts.
...