Skip to content

Instantly share code, notes, and snippets.

@indranil32
Last active April 1, 2021 08:18
Show Gist options
  • Save indranil32/6b3a514fd9104c0fbd007b6db10d9c26 to your computer and use it in GitHub Desktop.
Save indranil32/6b3a514fd9104c0fbd007b6db10d9c26 to your computer and use it in GitHub Desktop.
Showcashing Deadlock in Java/Groovy
class RunnableThread implements Runnable {
def obj1Private
def obj2Private
public RunnableThread(paramObj1, paramObj2) {
obj1Private = paramObj1
obj2Private = paramObj2
}
@Override
public void run(){
synchronized(obj1Private) {
println "synchronized on obj1 " + Thread.currentThread().getName()
Thread.sleep(1000)
synchronized(obj2Private) {
println "synchronized on obj2 " + Thread.currentThread().getName()
}
}
}
}
def obj1 = new String("obj1")
def obj2 = new String("obj2")
def t1 = new Thread(new RunnableThread(obj1, obj2), "t1")
t1.start();
def t2 = new Thread(new RunnableThread(obj2, obj1), "t2")
t2.start()
Thread.sleep(2000);
// jstack <pid>
//Found one Java-level deadlock:
//=============================
//"t2":
// waiting to lock monitor 0x0000000025ec3648 (object 0x000000071b72f440, a java.lang.String),
// which is held by "t1"
//"t1":
// waiting to lock monitor 0x000000002a38a508 (object 0x000000071b72f4e0, a java.lang.String),
// which is held by "t2"
//
//Java stack information for the threads listed above:
//===================================================
//"t2":
// at RunnableThread.run(SimpleDeadLock.groovy:14)
// - waiting to lock <0x000000071b72f440> (a java.lang.String)
// - locked <0x000000071b72f4e0> (a java.lang.String)
// at java.lang.Thread.run(Thread.java:748)
//"t1":
// at RunnableThread.run(SimpleDeadLock.groovy:14)
// - waiting to lock <0x000000071b72f4e0> (a java.lang.String)
// - locked <0x000000071b72f440> (a java.lang.String)
// at java.lang.Thread.run(Thread.java:748)
//
//Found 1 deadlock.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment