Skip to content

Commit 27bad3d

Browse files
committed
A simple deadlock in java with 2 threads
1 parent c112c0f commit 27bad3d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.rampatra.threads;
2+
3+
4+
import java.lang.management.ManagementFactory;
5+
import java.lang.management.ThreadMXBean;
6+
7+
/**
8+
* @author rampatra
9+
* @since 2019-03-13
10+
*/
11+
public class SimpleDeadlock implements Runnable {
12+
13+
private final Object obj1;
14+
private final Object obj2;
15+
16+
private SimpleDeadlock(Object obj1, Object obj2) {
17+
this.obj1 = obj1;
18+
this.obj2 = obj2;
19+
}
20+
21+
public void run() {
22+
try {
23+
synchronized (obj1) {
24+
// sleep for some time so that the next thread starts and acquires the other lock in the mean time
25+
Thread.sleep(5000);
26+
synchronized (obj2) {
27+
System.out.println("No deadlock!");
28+
}
29+
}
30+
} catch (InterruptedException e) {
31+
throw new RuntimeException(e);
32+
}
33+
}
34+
35+
public static void main(String[] args) {
36+
37+
Object obj1 = new Object();
38+
Object obj2 = new Object();
39+
40+
Thread thread1 = new Thread(new SimpleDeadlock(obj1, obj2));
41+
Thread thread2 = new Thread(new SimpleDeadlock(obj2, obj1));
42+
43+
thread1.start();
44+
thread2.start();
45+
46+
// a way to detect deadlocks, although an expensive one
47+
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
48+
while (true) {
49+
long[] deadlock = threadMXBean.findDeadlockedThreads();
50+
if (deadlock != null && deadlock.length > 0) {
51+
System.out.println("Deadlock detected, exiting now...");
52+
System.exit(1);
53+
}
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)