Created
September 6, 2012 17:38
-
-
Save mebubo/3658855 to your computer and use it in GitHub Desktop.
A really bad implementation of a 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
public class Deadlock { | |
private static final Object pause = new Object(); | |
private static volatile boolean proceed; | |
private static class Waiting { | |
volatile boolean waiting; | |
} | |
private static class DeadlockingThread extends Thread { | |
Object lock1; | |
Object lock2; | |
Waiting waiting; | |
DeadlockingThread(Object lock1, Object lock2, Waiting waiting) { | |
this.lock1 = lock1; | |
this.lock2 = lock2; | |
this.waiting = waiting; | |
} | |
@Override | |
public void run() { | |
synchronized (lock1) { | |
synchronized (pause) { | |
while (!proceed) { | |
try { | |
waiting.waiting = true; | |
pause.wait(); | |
} catch (InterruptedException e) { | |
} | |
} | |
} | |
System.out.println(String.format( | |
"Thread %s synched on %s synching on %s", Thread | |
.currentThread().getName(), lock1, lock2)); | |
synchronized (lock2) { | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Object lock1 = new Object(); | |
Object lock2 = new Object(); | |
Waiting waiting1 = new Waiting(); | |
Waiting waiting2 = new Waiting(); | |
new DeadlockingThread(lock1, lock2, waiting1).start(); | |
new DeadlockingThread(lock2, lock1, waiting2).start(); | |
while (!(waiting1.waiting && waiting2.waiting)) { | |
try { | |
Thread.sleep(100); | |
} catch (InterruptedException e) { | |
} | |
} | |
proceed = true; | |
synchronized (pause) { | |
pause.notifyAll(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment