I came across a deadlock scenario which can be summarized as the StaticDeadlock class shown below.
This simple program will freeze at o.getClass(). Here's my speculation of what happened, but can someone explain it better?
1) the program enters StaticDeadlock static block
2) thread starts
3) main thread is put in wait for thread to finish, hence can't finish the static block
4) inside thread it access StaticDeadlock.o but StaticDeadlock's static block is not finished yet. Hence the program freezes?
public class StaticDeadlock
{
private static final Object o = new Object();
static {
MyThread thread = new MyThread();
thread.start();
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main (String[] args)
{
System.out.println("all is well.");
}
static class MyThread extends Thread
{
@Override
public void run ()
{
System.out.println("inside mythread");
o.getClass();
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…