Skip to content

Instantly share code, notes, and snippets.

@alf239
Created January 16, 2012 13:47
Show Gist options
  • Select an option

  • Save alf239/1620950 to your computer and use it in GitHub Desktop.

Select an option

Save alf239/1620950 to your computer and use it in GitHub Desktop.
Deadlock in Java
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) {
}
}
}
}
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) {
}
}
}
}
@alf239
Copy link
Author

alf239 commented Jan 16, 2012

Still ugly, and uses new primitives.

@alf239
Copy link
Author

alf239 commented Jan 16, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment