Acquiring two locks in an inconsistent order may result in deadlock if two threads simultaneously attempt to acquire the locks, and each thread succeeds in acquiring one lock prior to being able to acquire the other lock.

To guard against deadlock, use one of the following alternatives:

In the following example, one method acquires primaryLock followed by savingsLock, and another method acquires these locks in reverse order. This may result in deadlock if the two methods are invoked by two threads simultaneously, and each thread acquires one of the two locks prior to being able to acquire the other one.

One way to address the issue in the above example is to reverse the lock order in transferToPrimary to match the lock order in transferToSecondary.

  • SEI CERT Oracle Coding Standard for Java: LCK07-J. Avoid deadlock by requesting and releasing locks in the same order.
  • Java Language Specification: Synchronization.
  • Java API Specification: ReentrantLock.