-
-
Save yshavit/6f734868cbda14794380 to your computer and use it in GitHub Desktop.
Intentional deadlock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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