Skip to content

Instantly share code, notes, and snippets.

@yshavit
Created November 8, 2013 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yshavit/6f734868cbda14794380 to your computer and use it in GitHub Desktop.
Save yshavit/6f734868cbda14794380 to your computer and use it in GitHub Desktop.
Intentional deadlock
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Locky {
private static class Boomer implements Runnable {
private final Lock lockA;
private final Lock lockB;
public Boomer(Lock lockA, Lock lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
try {
lockA.lock();
try {
Thread.sleep(500);
lockB.lock();
lockB.unlock();
} finally {
lockA.unlock();
}
} catch (InterruptedException e) {
e.printStackTrace(); // Not good for production, good enough for this demo
}
}
}
public static void main(String[] args) {
Lock l1 = new ReentrantLock();
Lock l2 = new ReentrantLock();
Thread t1 = new Thread(new Boomer(l1, l2));
Thread t2 = new Thread(new Boomer(l2, l1));
t1.start();
t2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment