Engineering Full Stack Apps with Java and JavaScript
Lock ordering deadlock is caused when using different order of acquiring locks when locking on multiple objects. The solution is also simple: either acquire only one lock at a time or when acquiring multiple locks, acquire them in same order, whenever feasible.
A lock ordering can be a simple one as we saw in a previous note (where we can directly see the order of acquiring) or a dynamic one (where the order may be decided by external input).
package deadlock;
public class DynamicLockOrderingDeadlock {
final static Object lockObject1 = new Object();
final static Object lockObject2 = new Object();
public static void method1(Object obj1, Object obj2) {
synchronized (obj1) { // Locking on obj1
System.out.println(Thread.currentThread().getName()
+ ": Got "+obj1 +". Trying for "+obj2);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) // Locking on obj2
{
System.out.println(Thread.currentThread().getName()
+ ": Got "+obj2);
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
DynamicLockOrderingDeadlock.method1(lockObject1, lockObject2);
}
};
t1.setName("Thread A");
t1.start();
Thread t2 = new Thread() {
public void run() {
DynamicLockOrderingDeadlock.method1(lockObject2, lockObject1);
}
};
t2.setName("Thread B");
t2.start();
}
}
Even though method1 looks like calling the objects in order, as you can see form the main program, the order is dependent on the actual objects passed during runtime.
We will see a possible solution to this problem next.
Java Concurrency in Practice by Brian Goetz, David Holmes, DOug Lea, Tim Peierls, Joshua Bloch and Joseph Bowbeer.