Site Search:

LeftRightDeadlock.java

 LeftRightDeadlock.java

/**
* LeftRightDeadlock
*
* Simple lock-ordering deadlock
*
*/
public class LeftRightDeadlock {
private final Object left = new Object();
private final Object right = new Object();

public void leftRight() {
synchronized (left) {
synchronized (right) {
doSomething();
}
}
}

public void rightLeft() {
synchronized (right) {
synchronized (left) {
doSomethingElse();
}
}
}

void doSomething() {
for(int i = 0; i < 10000; i++) {
int j = i * i;
}
}

void doSomethingElse() {
for(int i = 0; i < 10000; i++) {
int j = i * i;
}
}

public static void main(String...args) {
LeftRightDeadlock lrdl = new LeftRightDeadlock();
for(int i = 0; i < 1000; i++) {
new Thread(() -> {
lrdl.leftRight();
lrdl.rightLeft();
}).start();
}
}
}

This program is prone to a simple lock-ordering deadlock because it defines two methods that acquire the same two locks (left and right) in opposite orders. The leftRight method locks left first, then right, while rightLeft locks right first, then left. When multiple threads call these methods concurrently, it's possible for one thread to hold the left lock and wait for right, while another holds right and waits for left, causing both to block forever and resulting in a deadlock.

No comments:

Post a Comment