使用Jconsole分析死锁
作者:互联网
我正在运行一个导致死锁的简单程序.
final String resource1 = "santanu";
final String resource2 = "sahoo";
System.out.println(Integer.toHexString(resource1.hashCode()) );
System.out.println(Integer.toHexString(resource2.hashCode()) );
Thread t1 = new Thread(){
public void run()
{
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
Thread t2 = new Thread(){
public void run()
{
synchronized (resource2) {
try {
System.out.println("Thread 2: locked resource 2");
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
以下是预期产量
6f3700d4
6823b3a
Thread 1: locked resource 1
Thread 2: locked resource 2
现在我解雇了jps命令并找到了这个java程序的PID并使用了jconsole< pid>命令查看死锁.
下面是jconsole中的堆栈跟踪
Name: Thread-1
State: BLOCKED on java.lang.String@4ad61aef owned by: Thread-0
Total blocked: 1 Total waited: 1
Stack trace:
com.cmc.santanusol$2.run(santanusol.java:49)
- locked java.lang.String@4406cef4
现在我的问题是为什么jconsole stacktrace显示不同对象的HexString(java.lang.String @)与我在前两个sysout中打印的值相比较?
更确切地说,为什么6f3700d4和6823b3a值没有出现在jconsole输出中?
解决方法:
问题是String覆盖了hashCode.使用
System.out.println(Integer.toHexString(System.identityHashCode(resource1)));
System.out.println(Integer.toHexString(System.identityHashCode(resource2)));
用于调试.
背景:对象返回
getClass().getName() + "@" + Integer.toHexString(hashCode());
在toString中,但String和其他类重写toString(使用在此上下文中没有帮助的字符串),因此JConsole显示原始Object.toString显示的信息.
标签:java,multithreading,deadlock,jconsole 来源: https://codeday.me/bug/20190706/1399070.html