Java TheadDump

更多 Java 并发编程方面的文章,请参见文集《Java 并发编程》


基本使用

首先使用 jps -l 查找当前所有的 Java 进程。
随后使用 jstack -pid 查看特定 Java 进行的 Thread Dump,如果需要将结果导出到文件,可以使用 jstack -pid > dump.out

Thread Dump 包含的内容

  • thread name:线程名
  • thread id:线程 ID
  • java.lang.Thread.State:线程状态,包括:
    • NEW
    • RUNNABLE
    • BLOCKED:Waiting for a monitor lock,等待进入 synchronized 代码块
    • WAITING:包括三种情况:
      • 当前线程调用了不带参数的 obj.wait()
      • 其他线程调用了不带参数的 t2.join()
      • 调用了 LockSupport.park()
    • TIMED_WAITING:包括三种情况:
      • 当前线程调用了带参数的 obj.wait(1000)
      • 其他线程调用了带参数的 t2.join(1000)
      • 当前线程调用了 Thread.sleep(1000)
      • 调用了 LockSupport.parkNanos()
      • 调用了 LockSupport.parkUntil()
    • TERMINATED
  • Stack Trace:线程执行路径
  • 锁定了哪些资源,在等待哪些资源

示例

执行一段导致死锁的 Java 代码,参见 Java 死锁 DeadLock,随后导出其 TheadDump 文件。

其中的部分内容如下:

"Thread-1" #12 prio=5 os_prio=0 tid=0x000000001d5f7000 nid=0x2c48 waiting for monitor entry [0x000000001ea6f000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at DeadLockThread.run(DeadLockTesting.java:57)
    - waiting to lock <0x000000076b2ba340> (a java.lang.Object)
    - locked <0x000000076b2ba350> (a java.lang.Object)

"Thread-0" #11 prio=5 os_prio=0 tid=0x000000001d5e4000 nid=0x2f7c waiting for monitor entry [0x000000001e7cf000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at DeadLockThread.run(DeadLockTesting.java:57)
    - waiting to lock <0x000000076b2ba350> (a java.lang.Object)
    - locked <0x000000076b2ba340> (a java.lang.Object)

Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x000000001c13c338 (object 0x000000076b2ba340, a java.lang.Object),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x000000001c13c1d8 (object 0x000000076b2ba350, a java.lang.Object),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
    at DeadLockThread.run(DeadLockTesting.java:57)
    - waiting to lock <0x000000076b2ba340> (a java.lang.Object)
    - locked <0x000000076b2ba350> (a java.lang.Object)
"Thread-0":
    at DeadLockThread.run(DeadLockTesting.java:57)
    - waiting to lock <0x000000076b2ba350> (a java.lang.Object)
    - locked <0x000000076b2ba340> (a java.lang.Object)

Found 1 deadlock.

可以看出:

  • Thread-1 锁定了0x000000076b2ba350, 在等待 monitor 0x000000076b2ba340
  • Thread-0 锁定了0x000000076b2ba340,在等待 monitor 0x000000076b2ba350
  • 因此发现了一个死锁

你可能感兴趣的:(Java TheadDump)