Created
January 16, 2012 13:47
-
-
Save alf239/1620950 to your computer and use it in GitHub Desktop.
Deadlock in Java
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 implements Runnable { | |
private final Object a; | |
private final Object b; | |
private final static CountDownLatch latch = new CountDownLatch(2); | |
public Deadlock(Object a, Object b) { | |
this.a = a; | |
this.b = b; | |
} | |
public synchronized static void main(String[] args) throws InterruptedException { | |
new Thread(new Deadlock("a", "b")).start(); | |
new Thread(new Deadlock("b", "a")).start(); | |
} | |
@Override | |
public synchronized void run() { | |
synchronized (a) { | |
latch.countDown(); | |
try { | |
latch.await(); | |
} catch (InterruptedException ignored) { | |
} | |
synchronized (b) { | |
} | |
} | |
} | |
} |
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 SynchronizedDeadlock implements Runnable { | |
public synchronized static void main(String[] args) throws InterruptedException { | |
synchronized ("a") { | |
new Thread(new SynchronizedDeadlock()).start(); | |
"a".wait(); | |
} | |
synchronized ("") { | |
} | |
} | |
@Override | |
public void run() { | |
synchronized ("") { | |
synchronized ("a") { | |
"a".notifyAll(); | |
} | |
synchronized (SynchronizedDeadlock.class) { | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still ugly, and uses new primitives.