JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解 – 实例分析



JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解 – 实例分析.

工具介绍部分:

 

现实企业级Java开发中,有时候我们会碰到下面这些问题:

  • OutOfMemoryError,内存不足
  • 内存泄露
  • 线程死锁
  • 锁争用(Lock Contention)
  • Java进程消耗CPU过高
  • ……

这些问题在日常开发中可能被很多人忽视(比如有的人遇到上面的问题只是重启服务器或者调大内存,而不会深究问题根源),但能够理解并解决这些问题是Java程序员进阶的必备要求。

 

 

A、 jps(Java Virtual Machine Process Status Tool)

 

jps主要用来输出JVM中运行的进程状态信息。语法格式如下:

 

Java代码  收藏代码
  1. jps [options] [hostid]

如果不指定hostid就默认为当前主机或服务器。

 

命令行参数选项说明如下:

 

Java代码  收藏代码
  1. -q 不输出类名、Jar名和传入main方法的参数
  2. -m 输出传入main方法的参数
  3. -l 输出main类或Jar的全限名
  4. -v 输出传入JVM的参数

比如下面:

 

 

Java代码  收藏代码
  1. root@ubuntu:/# jps -m -l
  2. 2458 org.artifactory.standalone.main.Main /usr/local/artifactory-2.2.5/etc/jetty.xml
  3. 29920 com.sun.tools.hat.Main -port 9998 /tmp/dump.dat
  4. 3149 org.apache.catalina.startup.Bootstrap start
  5. 30972 sun.tools.jps.Jps -m -l
  6. 8247 org.apache.catalina.startup.Bootstrap start
  7. 25687 com.sun.tools.hat.Main -port 9999 dump.dat
  8. 21711 mrf-center.jar

 

 

B、 jstack

 

jstack主要用来查看某个Java进程内的线程堆栈信息。语法格式如下:

 

Java代码  收藏代码
  1. jstack [option] pid
  2. jstack [option] executable core
  3. jstack [option] [server-id@]remote-hostname-or-ip

 

Java代码  收藏代码
  1. 命令行参数选项说明如下:

 

Java代码  收藏代码
  1. -l long listings,会打印出额外的锁信息,在发生死锁时可以用jstack -l pid来观察锁持有情况
  2. -m mixed mode,不仅会输出Java堆栈信息,还会输出C/C++堆栈信息(比如Native方法)

 

 

jstack可以定位到线程堆栈,根据堆栈信息我们可以定位到具体代码,所以它在JVM性能调优中使用得非常多。下面我们来一个实例找出某个Java进程中最耗费CPU的Java线程并定位堆栈信息,用到的命令有ps、top、printf、jstack、grep。

第一步先找出Java进程ID,服务器上的Java应用名称为mrf-center:

 

 

Java代码  收藏代码
  1. root@ubuntu:/# ps -ef | grep mrf-center | grep -v grep
  2. root     21711     1  1 14:47 pts/3    00:02:10 java -jar mrf-center.jar
Java代码  收藏代码
  1. 得到进程ID为21711,第二步找出该进程内最耗费CPU的线程,可以使用
  2. 1)ps -Lfp pid
  3. 2)ps -mp pid -o THREAD, tid, time
  4. 3)top -Hp pid
  5. 用第三个,输出如下:

 

 

TIME列就是各个Java线程耗费的CPU时间,CPU时间最长的是线程ID为21742的线程,用

 

Java代码  收藏代码
  1. printf ”%x\n” 21742

得到21742的十六进制值为54ee,下面会用到。

 

OK,下一步终于轮到jstack上场了,它用来输出进程21711的堆栈信息,然后根据线程ID的十六进制值grep,如下:

 

Java代码  收藏代码
  1. root@ubuntu:/# jstack 21711 | grep 54ee
  2. “PollIntervalRetrySchedulerThread” prio=10 tid=0x00007f950043e000 nid=0x54ee in Object.wait()

可以看到CPU消耗在PollIntervalRetrySchedulerThread这个类的Object.wait(),我找了下我的代码,定位到下面的代码:

 

 

Java代码  收藏代码
  1. // Idle wait
  2. getLog().info(“Thread [" + getName() + "] is idle waiting…”);
  3. schedulerThreadState = PollTaskSchedulerThreadState.IdleWaiting;
  4. long now = System.currentTimeMillis();
  5. long waitTime = now + getIdleWaitTime();
  6. long timeUntilContinue = waitTime - now;
  7. synchronized(sigLock) {
  8.     try {
  9.         if(!halted.get()) {
  10.             sigLock.wait(timeUntilContinue);
  11.         }
  12.     }
  13.     catch (InterruptedException ignore) {
  14.     }
  15. }

它是轮询任务的空闲等待代码,上面的sigLock.wait(timeUntilContinue)就对应了前面的Object.wait()。

 

 

C、 jmap(Memory Map)和jhat(Java Heap Analysis Tool)

 

jmap用来查看堆内存使用状况,一般结合jhat使用。

 

jmap语法格式如下:

 

Java代码  收藏代码
  1. jmap [option] pid
  2. jmap [option] executable core
  3. jmap [option] [server-id@]remote-hostname-or-ip

如果运行在64位JVM上,可能需要指定-J-d64命令选项参数。

 

 

Java代码  收藏代码
  1. jmap -permstat pid

打印进程的类加载器和类加载器加载的持久代对象信息,输出:类加载器名称、对象是否存活(不可靠)、对象地址、父类加载器、已加载的类大小等信息,如下图:

 

 

使用jmap -heap pid查看进程堆内存使用情况,包括使用的GC算法、堆配置参数和各代中堆内存使用情况。比如下面的例子

 

Java代码  收藏代码
  1. root@ubuntu:/# jmap -heap 21711
  2. Attaching to process ID 21711, please wait…
  3. Debugger attached successfully.
  4. Server compiler detected.
  5. JVM version is 20.10-b01
  6. using thread-local object allocation.
  7. Parallel GC with 4 thread(s)
  8. Heap Configuration:
  9.    MinHeapFreeRatio = 40
  10.    MaxHeapFreeRatio = 70
  11.    MaxHeapSize      = 2067791872 (1972.0MB)
  12.    NewSize          = 1310720 (1.25MB)
  13.    MaxNewSize       = 17592186044415 MB
  14.    OldSize          = 5439488 (5.1875MB)
  15.    NewRatio         = 2
  16.    SurvivorRatio    = 8
  17.    PermSize         = 21757952 (20.75MB)
  18.    MaxPermSize      = 85983232 (82.0MB)
  19. Heap Usage:
  20. PS Young Generation
  21. Eden Space:
  22.    capacity = 6422528 (6.125MB)
  23.    used     = 5445552 (5.1932830810546875MB)
  24.    free     = 976976 (0.9317169189453125MB)
  25.    84.78829520089286% used
  26. From Space:
  27.    capacity = 131072 (0.125MB)
  28.    used     = 98304 (0.09375MB)
  29.    free     = 32768 (0.03125MB)
  30.    75.0% used
  31. To Space:
  32.    capacity = 131072 (0.125MB)
  33.    used     = 0 (0.0MB)
  34.    free     = 131072 (0.125MB)
  35.    0.0% used
  36. PS Old Generation
  37.    capacity = 35258368 (33.625MB)
  38.    used     = 4119544 (3.9287033081054688MB)
  39.    free     = 31138824 (29.69629669189453MB)
  40.    11.683876009235595% used
  41. PS Perm Generation
  42.    capacity = 52428800 (50.0MB)
  43.    used     = 26075168 (24.867218017578125MB)
  44.    free     = 26353632 (25.132781982421875MB)
  45.    49.73443603515625% used
  46.    ….

使用jmap -histo[:live] pid查看堆内存中的对象数目、大小统计直方图,如果带上live则只统计活对象,如下:

 

 

 

Java代码  收藏代码
  1. root@ubuntu:/# jmap -histo:live 21711 | more
  2.  num     #instances         #bytes  class name
  3. ———————————————-
  4.    1:         38445        5597736  <constMethodKlass>
  5.    2:         38445        5237288  <methodKlass>
  6.    3:          3500        3749504  <constantPoolKlass>
  7.    4:         60858        3242600  <symbolKlass>
  8.    5:          3500        2715264  <instanceKlassKlass>
  9.    6:          2796        2131424  <constantPoolCacheKlass>
  10.    7:          5543        1317400  [I
  11.    8:         13714        1010768  [C
  12.    9:          4752        1003344  [B
  13.   10:          1225         639656  <methodDataKlass>
  14.   11:         14194         454208  java.lang.String
  15.   12:          3809         396136  java.lang.Class
  16.   13:          4979         311952  [S
  17.   14:          5598         287064  [[I
  18.   15:          3028         266464  java.lang.reflect.Method
  19.   16:           280         163520  <objArrayKlassKlass>
  20.   17:          4355         139360  java.util.HashMap$Entry
  21.   18:          1869         138568  [Ljava.util.HashMap$Entry;
  22.   19:          2443          97720  java.util.LinkedHashMap$Entry
  23.   20:          2072          82880  java.lang.ref.SoftReference
  24.   21:          1807          71528  [Ljava.lang.Object;
  25.   22:          2206          70592  java.lang.ref.WeakReference
  26.   23:           934          52304  java.util.LinkedHashMap
  27.   24:           871          48776  java.beans.MethodDescriptor
  28.   25:          1442          46144  java.util.concurrent.ConcurrentHashMap$HashEntry
  29.   26:           804          38592  java.util.HashMap
  30.   27:           948          37920  java.util.concurrent.ConcurrentHashMap$Segment
  31.   28:          1621          35696  [Ljava.lang.Class;
  32.   29:          1313          34880  [Ljava.lang.String;
  33.   30:          1396          33504  java.util.LinkedList$Entry
  34.   31:           462          33264  java.lang.reflect.Field
  35.   32:          1024          32768  java.util.Hashtable$Entry
  36.   33:           948          31440  [Ljava.util.concurrent.ConcurrentHashMap$HashEntry;


class name是对象类型,说明如下:

 

 

Java代码  收藏代码
  1. B  byte
  2. C  char
  3. D  double
  4. F  float
  5. I  int
  6. J  long
  7. Z  boolean
  8. [  数组,如[I表示int[]
  9. [L+类名 其他对象

 

 

还有一个很常用的情况是:用jmap把进程内存使用情况dump到文件中,再用jhat分析查看。jmap进行dump命令格式如下:

 

Java代码  收藏代码
  1. <strong>jmap -dump:format=b,file=dumpFileName pid</strong>

 我一样地对上面进程ID为21711进行Dump:

 

 

Java代码  收藏代码
  1. root@ubuntu:/# jmap -dump:format=b,file=/tmp/dump.dat 21711
  2. Dumping heap to /tmp/dump.dat ...
  3. Heap dump file created

dump出来的文件可以用MAT、VisualVM等工具查看,这里用jhat查看:

 

 

 

Java代码  收藏代码
  1. root@ubuntu:/# jhat -port 9998 /tmp/dump.dat
  2. Reading from /tmp/dump.dat...
  3. Dump file created Tue Jan 28 17:46:14 CST 2014
  4. Snapshot read, resolving...
  5. Resolving 132207 objects...
  6. Chasing references, expect 26 dots..........................
  7. Eliminating duplicate references..........................
  8. Snapshot resolved.
  9. Started HTTP server on port 9998
  10. Server is ready.

注意如果Dump文件太大,可能需要加上-J-Xmx512m这种参数指定最大堆内存,即jhat -J-Xmx512m -port 9998 /tmp/dump.dat。然后就可以在浏览器中输入主机地址:9998查看了:

 

http://www.hongyanliren.com/wp-content/uploads/2014/11/174715_FTKZ_111708.png

上面红线框出来的部分大家可以自己去摸索下,最后一项支持OQL(对象查询语言)。

 

D、jstat(JVM统计监测工具)

 

语法格式如下:

 

Java代码  收藏代码
  1. jstat [ generalOption | outputOptions vmid [interval[s|ms] [count]] ]

vmid是Java虚拟机ID,在Linux/Unix系统上一般就是进程ID。interval是采样时间间隔。count是采样数目。比如下面输出的是GC信息,采样时间间隔为250ms,采样数为4:

 

Java代码  收藏代码
  1. root@ubuntu:/# jstat -gc 21711 250 4
  2.  S0C    S1C    S0U    S1U      EC       EU        OC         OU       PC     PU    YGC     YGCT    FGC    FGCT     GCT
  3. 192.0  192.0   64.0   0.0    6144.0   1854.9   32000.0     4111.6   55296.0 25472.7    702    0.431   3      0.218    0.649
  4. 192.0  192.0   64.0   0.0    6144.0   1972.2   32000.0     4111.6   55296.0 25472.7    702    0.431   3      0.218    0.649
  5. 192.0  192.0   64.0   0.0    6144.0   1972.2   32000.0     4111.6   55296.0 25472.7    702    0.431   3      0.218    0.649
  6. 192.0  192.0   64.0   0.0    6144.0   2109.7   32000.0     4111.6   55296.0 25472.7    702    0.431   3      0.218    0.649

要明白上面各列的意义,先看JVM堆内存布局:

 

可以看出:

Java代码  收藏代码
  1. 堆内存 = 年轻代 + 年老代 + 永久代
  2. 年轻代 = Eden区 + 两个Survivor区(From和To)

现在来解释各列含义:

Java代码  收藏代码
  1. S0C、S1C、S0U、S1U:Survivor 0/1区容量(Capacity)和使用量(Used)
  2. EC、EU:Eden区容量和使用量
  3. OC、OU:年老代容量和使用量
  4. PC、PU:永久代容量和使用量
  5. YGC、YGT:年轻代GC次数和GC耗时
  6. FGC、FGCT:Full GC次数和Full GC耗时
  7. GCT:GC总耗时

 

E、hprof(Heap/CPU Profiling Tool)

hprof能够展现CPU使用率,统计堆内存使用情况。

语法格式如下:

Java代码  收藏代码
  1. java -agentlib:hprof[=options] ToBeProfiledClass
  2. java -Xrunprof[:options] ToBeProfiledClass
  3. javac -J-agentlib:hprof[=options] ToBeProfiledClass

完整的命令选项如下:

Java代码  收藏代码
  1. Option Name and Value  Description                    Default
  2. ———————  ———–                    ——-
  3. heap=dump|sites|all    heap profiling                 all
  4. cpu=samples|times|old  CPU usage                      off
  5. monitor=y|n            monitor contention             n
  6. format=a|b             text(txt) or binary output     a
  7. file=<file>            write data to file             java.hprof[.txt]
  8. net=<host>:<port>      send data over a socket        off
  9. depth=<size>           stack trace depth              4
  10. interval=<ms>          sample interval in ms          10
  11. cutoff=<value>         output cutoff point            0.0001
  12. lineno=y|n             line number in traces?         y
  13. thread=y|n             thread in traces?              n
  14. doe=y|n                dump on exit?                  y
  15. msa=y|n                Solaris micro state accounting n
  16. force=y|n              force output to <file>         y
  17. verbose=y|n            print messages about dumps     y

 

来几个官方指南上的实例。

CPU Usage Sampling Profiling(cpu=samples)的例子:

Java代码  收藏代码
  1.  CPU Usage Sampling Profiling(cpu=samples)的例子:
  2. java -agentlib:hprof=cpu=samples,interval=20,depth=3 Hello
  3.     上面每隔20毫秒采样CPU消耗信息,堆栈深度为3,生成的profile文件名称是java.hprof.txt,在当前目录。
  4.     CPU Usage Times Profiling(cpu=times)的例子,它相对于CPU Usage Sampling Profile能够获得更加细粒度的CPU消耗信息,能够细到每个方法调用的开始和结束,它的实现使用了字节码注入技术(BCI):
  5. javac -J-agentlib:hprof=cpu=times Hello.java
  6.     Heap Allocation Profiling(heap=sites)的例子:
  7. javac -J-agentlib:hprof=heap=sites Hello.java
  8.     Heap Dump(heap=dump)的例子,它比上面的Heap Allocation Profiling能生成更详细的Heap Dump信息:
  9. javac -J-agentlib:hprof=heap=dump Hello.java
  10.     虽然在JVM启动参数中加入-Xrunprof:heap=sites参数可以生成CPU/Heap Profile文件,但对JVM性能影响非常大,不建议在线上服务器环境使用。

 

第二部分: 实例部分:

1、使用jstack来分析死锁问题:

上面说明中提到jstack 是一个可以返回在应用程序上运行的各种各样线程的一个完整转储的实用程序,您可以使用它查明问题。jstack [-l] <pid>,jpid可以通过使用jps命令来查看当前Java程序的jpid值,-l是可选参数,它可以显示线程阻塞/死锁情况

Java代码  收藏代码
  1. /**
  2.  * Dead lock example
  3.  *
  4.  * @author Josh Wang(Sheng)
  5.  *
  6.  * @email  josh_wang23@hotmail.com
  7.  */
  8. public class DeadLock2Live {
  9.     public static void main(String[] args) {
  10.         System.out.println(“ start the example —– ”);
  11.         final Object obj_1 = new Object(), obj_2 = new Object();
  12.         Thread t1 = new Thread(“t1″){
  13.             @Override
  14.             public void run() {
  15.                 synchronized (obj_1) {
  16.                     try {
  17.                         Thread.sleep(3000);
  18.                     } catch (InterruptedException e) {}
  19.                     synchronized (obj_2) {
  20.                         System.out.println(“thread t1 done.”);
  21.                     }
  22.                 }
  23.             }
  24.         };
  25.         Thread t2 = new Thread(“t2″){
  26.             @Override
  27.             public void run() {
  28.                 synchronized (obj_2) {
  29.                     try {
  30.                         Thread.sleep(3000);
  31.                     } catch (InterruptedException e) {}
  32.                     synchronized (obj_1) {
  33.                         System.out.println(“thread t2 done.”);
  34.                     }
  35.                 }
  36.             }
  37.         };
  38.         t1.start();
  39.         t2.start();
  40.     }
  41. }

 

以上DeadLock类是一个死锁的例子,假使在我们不知情的情况下,运行DeadLock后,发现等了N久都没有在屏幕打印线程完成信息。这个时候我们就可以使用jps查看该程序的jpid值和使用jstack来生产堆栈结果问题。

Java代码  收藏代码
  1. java -cp deadlock.jar DeadLock &

 

Java代码  收藏代码
  1. $ jps
  2.   3076 Jps
  3.   448 DeadLock
  4. $ jstack -l 448 > deadlock.jstack

结果文件deadlock.jstack内容如下:

Java代码  收藏代码
  1. 2014-11-29 13:31:06
  2. Full thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):
  3. “Attach Listener” daemon prio=5 tid=0x00007fd9d4002800 nid=0x440b waiting on condition [0x0000000000000000]
  4.    java.lang.Thread.State: RUNNABLE
  5.    Locked ownable synchronizers:
  6.     - None
  7. “DestroyJavaVM” prio=5 tid=0x00007fd9d4802000 nid=0×1903 waiting on condition [0x0000000000000000]
  8.    java.lang.Thread.State: RUNNABLE
  9.    Locked ownable synchronizers:
  10.     - None
  11. “t2″ prio=5 tid=0x00007fd9d30ac000 nid=0×5903 waiting for monitor entry [0x000000011da46000]
  12.    java.lang.Thread.State: BLOCKED (on object monitor)
  13.     at DeadLock$2.run(DeadLock.java:38)
  14.     - waiting to lock <0x00000007aaba7e58> (a java.lang.Object)
  15.     - locked <0x00000007aaba7e68> (a java.lang.Object)
  16.    Locked ownable synchronizers:
  17.     - None
  18. “t1″ prio=5 tid=0x00007fd9d30ab800 nid=0×5703 waiting for monitor entry [0x000000011d943000]
  19.    java.lang.Thread.State: BLOCKED (on object monitor)
  20.     at DeadLock$1.run(DeadLock.java:23)
  21.     - waiting to lock <0x00000007aaba7e68> (a java.lang.Object)
  22.     - locked <0x00000007aaba7e58> (a java.lang.Object)
  23.    Locked ownable synchronizers:
  24.     - None
  25. “Service Thread” daemon prio=5 tid=0x00007fd9d2809000 nid=0×5303 runnable [0x0000000000000000]
  26.    java.lang.Thread.State: RUNNABLE
  27.    Locked ownable synchronizers:
  28.     - None
  29. “C2 CompilerThread1″ daemon prio=5 tid=0x00007fd9d304e000 nid=0×5103 waiting on condition [0x0000000000000000]
  30.    java.lang.Thread.State: RUNNABLE
  31.    Locked ownable synchronizers:
  32.     - None
  33. “C2 CompilerThread0″ daemon prio=5 tid=0x00007fd9d2800800 nid=0x4f03 waiting on condition [0x0000000000000000]
  34.    java.lang.Thread.State: RUNNABLE
  35.    Locked ownable synchronizers:
  36.     - None
  37. “Signal Dispatcher” daemon prio=5 tid=0x00007fd9d3035000 nid=0x4d03 runnable [0x0000000000000000]
  38.    java.lang.Thread.State: RUNNABLE
  39.    Locked ownable synchronizers:
  40.     - None
  41. “Finalizer” daemon prio=5 tid=0x00007fd9d2013000 nid=0×3903 in Object.wait() [0x000000011d18d000]
  42.    java.lang.Thread.State: WAITING (on object monitor)
  43.     at java.lang.Object.wait(Native Method)
  44.     - waiting on <0x00000007aaa85608> (a java.lang.ref.ReferenceQueue$Lock)
  45.     at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
  46.     - locked <0x00000007aaa85608> (a java.lang.ref.ReferenceQueue$Lock)
  47.     at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
  48.     at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
  49.    Locked ownable synchronizers:
  50.     - None
  51. “Reference Handler” daemon prio=5 tid=0x00007fd9d2012000 nid=0×3703 in Object.wait() [0x000000011d08a000]
  52.    java.lang.Thread.State: WAITING (on object monitor)
  53.     at java.lang.Object.wait(Native Method)
  54.     - waiting on <0x00000007aaa85190> (a java.lang.ref.Reference$Lock)
  55.     at java.lang.Object.wait(Object.java:503)
  56.     at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
  57.     - locked <0x00000007aaa85190> (a java.lang.ref.Reference$Lock)
  58.    Locked ownable synchronizers:
  59.     - None
  60. “VM Thread” prio=5 tid=0x00007fd9d5011000 nid=0×3503 runnable
  61. “GC task thread#0 (ParallelGC)” prio=5 tid=0x00007fd9d200b000 nid=0×2503 runnable
  62. “GC task thread#1 (ParallelGC)” prio=5 tid=0x00007fd9d200b800 nid=0×2703 runnable
  63. “GC task thread#2 (ParallelGC)” prio=5 tid=0x00007fd9d200c800 nid=0×2903 runnable
  64. “GC task thread#3 (ParallelGC)” prio=5 tid=0x00007fd9d200d000 nid=0x2b03 runnable
  65. “GC task thread#4 (ParallelGC)” prio=5 tid=0x00007fd9d200d800 nid=0x2d03 runnable
  66. “GC task thread#5 (ParallelGC)” prio=5 tid=0x00007fd9d200e000 nid=0x2f03 runnable
  67. “GC task thread#6 (ParallelGC)” prio=5 tid=0x00007fd9d200f000 nid=0×3103 runnable
  68. “GC task thread#7 (ParallelGC)” prio=5 tid=0x00007fd9d200f800 nid=0×3303 runnable
  69. “VM Periodic Task Thread” prio=5 tid=0x00007fd9d3033800 nid=0×5503 waiting on condition
  70. JNI global references: 114
  71. Found one Java-level deadlock:
  72. =============================
  73. <span style=”color: #ff0000;”><strong>”t2″:
  74.   waiting to lock monitor 0x00007fd9d30aebb8 (object 0x00000007aaba7e58, a java.lang.Object),
  75.   which is held by ”t1″
  76. “t1″:
  77.   waiting to lock monitor 0x00007fd9d28128b8 (object 0x00000007aaba7e68, a java.lang.Object),
  78.   which is held by ”t2″
  79. Java stack information for the threads listed above:</strong></span>
  80. ===================================================
  81. <span style=”color: #ff0000;”>”t2″:
  82.     at DeadLock$2.run(DeadLock.java:38)
  83.     - waiting to lock <0x00000007aaba7e58> (a java.lang.Object)
  84.     - locked <0x00000007aaba7e68> (a java.lang.Object)
  85. “t1″:
  86.     at DeadLock$1.run(DeadLock.java:23)
  87.     - waiting to lock <0x00000007aaba7e68> (a java.lang.Object)
  88.     - locked <0x00000007aaba7e58> (a java.lang.Object)
  89. Found 1 deadlock.
  90. </span>

从这个结果文件我们一看到发现了一个死锁,具体是线程t2在等待线程t1,而线程t1在等待线程t2造成的,同时也记录了线程的堆栈和代码行数,通过这个堆栈和行数我们就可以去检查对应的代码块,从而发现问题和解决问题。

可通过下面的代码解决死锁问题:

Java代码  收藏代码
  1. import java.util.concurrent.locks.Lock;
  2. import java.util.concurrent.locks.ReentrantLock;
  3. /**
  4.  * Dead lock example
  5.  *
  6.  * @author Josh Wang(Sheng)
  7.  *
  8.  * @email  josh_wang23@hotmail.com
  9.  */
  10. public class DeadLock2Live {
  11.     public static void main(String[] args) {
  12.         System.out.println(“ start the example —– ”);
  13.         final Lock lock = new ReentrantLock();
  14.         Thread t1 = new Thread(“t1″) {
  15.             @Override
  16.             public void run() {
  17.                 try {
  18.                 lock.lock();
  19.                     Thread.sleep(3000);
  20.                     System.out.println(“thread t1 done.”);
  21.                 } catch (InterruptedException e) {
  22.                     e.printStackTrace();
  23.                 } finally {
  24.                     lock.unlock();
  25.                 }
  26.             }
  27.             };
  28.         Thread t2 = new Thread(“t2″) {
  29.             @Override
  30.             public void run() {
  31.                 try {
  32.                     lock.lock();
  33.                     Thread.sleep(3000);
  34.                     System.out.println(“thread t2 done.”);
  35.                 }  catch (InterruptedException e) {
  36.                     e.printStackTrace();
  37.                 } finally {
  38.                     lock.unlock();
  39.                 }
  40.             }
  41.         };
  42.         t1.start();
  43.         t2.start();
  44. }
  45. }

 

2、继续使用jstack来分析HashMap在多线程情况下的死锁问题:

对于如下代码,使用10个线程来处理提交的2000个任务,每个任务会分别循环往hashmap中分别存入和取出1000个数,通过测试发现,程序并不能完整执行完成。[PS:该程序能不能成功执行完,有时也取决于所使用的服务器的运行状况,我在笔记本上测试的时候,大多时候该程序不能成功执行完成,后者会出现CPU转速加快,发热等情况]

 

Java代码  收藏代码
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutionException;
  5. import java.util.concurrent.ExecutorService;
  6. import java.util.concurrent.Executors;
  7. /**
  8.  *
  9.  */
  10. /**
  11.  * @author Josh Wang(Sheng)
  12.  *
  13.  * @email  josh_wang23@hotmail.com
  14.  */
  15. public class HashMapDeadLock implements Callable<Integer> {
  16.     private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
  17.     private static Map<Integer, Integer> results = new HashMap<>();
  18.     @Override
  19.     public Integer call() throws Exception {
  20.         results.put(1, 1);
  21.         results.put(2, 2);
  22.         results.put(3, 3);
  23.         for (int i = 0; i < 1000; i++) {
  24.             results.put(i, i);
  25.         }
  26.         Thread.sleep(1000);
  27.         for (int i= 0; i < 1000; i++) {
  28.             results.remove(i);
  29.         }
  30.         System.out.println(“ —- ” + Thread.currentThread().getName()  + ”     ” + results.get(0));
  31.         return results.get(1);
  32.     }
  33.     public static void main(String[] args) throws InterruptedException, ExecutionException {
  34.         try {
  35.             for (int i = 0; i < 2000; i++) {
  36.                     HashMapDeadLock hashMapDeadLock  = new HashMapDeadLock();
  37. //                  Future<Integer> future = threadPool.submit(hashMapDeadLock);
  38. //                  future.get();
  39.                     threadPool.submit(hashMapDeadLock);
  40.                 }
  41.         } catch (Exception e) {
  42.             e.printStackTrace();
  43.         } finally {
  44.             threadPool.shutdown();
  45.         }
  46.     }
  47. }

 

1) 使用jps查看线程可得:

Java代码  收藏代码
  1. 43221 Jps
  2. 30056
  3. 43125 HashMapDeadLock

 

2)使用jstack导出多线程栈区信息:

Java代码  收藏代码
  1. jstack -l 43125 > hash.jstack

 

3) hash.jstack的内容如下:

Java代码  收藏代码
  1. 2014-11-29 18:14:22
  2. Full thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):
  3. “Attach Listener” daemon prio=5 tid=0x00007f83ee08a000 nid=0x5d07 waiting on condition [0x0000000000000000]
  4.    java.lang.Thread.State: RUNNABLE
  5.    Locked ownable synchronizers:
  6.     - None
  7. “DestroyJavaVM” prio=5 tid=0x00007f83eb016800 nid=0×1903 waiting on condition [0x0000000000000000]
  8.    java.lang.Thread.State: RUNNABLE
  9.    Locked ownable synchronizers:
  10.     - None
  11. “pool-1-thread-10″ prio=5 tid=0x00007f83ec80a000 nid=0×6903 runnable [0x000000011cd19000]
  12.    java.lang.Thread.State: RUNNABLE
  13.     at java.util.HashMap.transfer(HashMap.java:601)
  14.     at java.util.HashMap.resize(HashMap.java:581)
  15.     at java.util.HashMap.addEntry(HashMap.java:879)
  16.     at java.util.HashMap.put(HashMap.java:505)
  17.     <strong><span style=”color: #ff0000;”>at HashMapDeadLock.call(HashMapDeadLock.java:30)
  18.     at HashMapDeadLock.call(HashMapDeadLock.java:1)</span></strong>
  19.     at java.util.concurrent.FutureTask.run(FutureTask.java:262)
  20.     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  21.     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  22.     at java.lang.Thread.run(Thread.java:745)
  23.    Locked ownable synchronizers:
  24.     - <0x00000007aaba84c8> (a java.util.concurrent.ThreadPoolExecutor$Worker)
  25. “Service Thread” daemon prio=5 tid=0x00007f83eb839800 nid=0×5303 runnable [0x0000000000000000]
  26.    java.lang.Thread.State: RUNNABLE
  27.    Locked ownable synchronizers:
  28.     - None
  29. “C2 CompilerThread1″ daemon prio=5 tid=0x00007f83ee002000 nid=0×5103 waiting on condition [0x0000000000000000]
  30.    java.lang.Thread.State: RUNNABLE
  31.    Locked ownable synchronizers:
  32.     - None
  33. “C2 CompilerThread0″ daemon prio=5 tid=0x00007f83ee000000 nid=0x4f03 waiting on condition [0x0000000000000000]
  34.    java.lang.Thread.State: RUNNABLE
  35.    Locked ownable synchronizers:
  36.     - None
  37. “Signal Dispatcher” daemon prio=5 tid=0x00007f83ec04c800 nid=0x4d03 runnable [0x0000000000000000]
  38.    java.lang.Thread.State: RUNNABLE
  39.    Locked ownable synchronizers:
  40.     - None
  41. “Finalizer” daemon prio=5 tid=0x00007f83eb836800 nid=0×3903 in Object.wait() [0x000000011bc58000]
  42.    java.lang.Thread.State: WAITING (on object monitor)
  43.     at java.lang.Object.wait(Native Method)
  44.     - waiting on <0x00000007aaa85608> (a java.lang.ref.ReferenceQueue$Lock)
  45.     at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
  46.     - locked <0x00000007aaa85608> (a java.lang.ref.ReferenceQueue$Lock)
  47.     at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
  48.     at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
  49.    Locked ownable synchronizers:
  50.     - None
  51. “Reference Handler” daemon prio=5 tid=0x00007f83eb01a800 nid=0×3703 in Object.wait() [0x000000011bb55000]
  52.    java.lang.Thread.State: WAITING (on object monitor)
  53.     at java.lang.Object.wait(Native Method)
  54.     - waiting on <0x00000007aaa85190> (a java.lang.ref.Reference$Lock)
  55.     at java.lang.Object.wait(Object.java:503)
  56.     at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
  57.     - locked <0x00000007aaa85190> (a java.lang.ref.Reference$Lock)
  58.    Locked ownable synchronizers:
  59.     - None
  60. “VM Thread” prio=5 tid=0x00007f83ed808800 nid=0×3503 runnable
  61. “GC task thread#0 (ParallelGC)” prio=5 tid=0x00007f83ec80d800 nid=0×2503 runnable
  62. “GC task thread#1 (ParallelGC)” prio=5 tid=0x00007f83ec80e000 nid=0×2703 runnable
  63. “GC task thread#2 (ParallelGC)” prio=5 tid=0x00007f83ec001000 nid=0×2903 runnable
  64. “GC task thread#3 (ParallelGC)” prio=5 tid=0x00007f83ec002000 nid=0x2b03 runnable
  65. “GC task thread#4 (ParallelGC)” prio=5 tid=0x00007f83ec002800 nid=0x2d03 runnable
  66. “GC task thread#5 (ParallelGC)” prio=5 tid=0x00007f83ec003000 nid=0x2f03 runnable
  67. “GC task thread#6 (ParallelGC)” prio=5 tid=0x00007f83ec003800 nid=0×3103 runnable
  68. “GC task thread#7 (ParallelGC)” prio=5 tid=0x00007f83ec004800 nid=0×3303 runnable
  69. “VM Periodic Task Thread” prio=5 tid=0x00007f83ec814800 nid=0×5503 waiting on condition
  70. JNI global references: 134

4)从红色高亮部分可看出,代码中的30行出问题了,即往hashmap中写入数据出问题了:

Java代码  收藏代码
  1. results.put(i, i);

 

很快就明白因为Hashmap不是线程安全的,所以问题就出在这个地方,我们可以使用线程安全的map即

ConcurrentHashMap后者HashTable来解决该问题:

 

Java代码  收藏代码
  1. import java.util.Map;
  2. import java.util.concurrent.Callable;
  3. import java.util.concurrent.ConcurrentHashMap;
  4. import java.util.concurrent.ExecutionException;
  5. import java.util.concurrent.ExecutorService;
  6. import java.util.concurrent.Executors;
  7. /**
  8.  *
  9.  */
  10. /**
  11.  * @author Josh Wang(Sheng)
  12.  *
  13.  * @email  josh_wang23@hotmail.com
  14.  */
  15. public class HashMapDead2LiveLock implements Callable<Integer> {
  16.     private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
  17.     private static Map<Integer, Integer> results = new ConcurrentHashMap<>();
  18.     @Override
  19.     public Integer call() throws Exception {
  20.         results.put(1, 1);
  21.         results.put(2, 2);
  22.         results.put(3, 3);
  23.         for (int i = 0; i < 1000; i++) {
  24.             results.put(i, i);
  25.         }
  26.         Thread.sleep(1000);
  27.         for (int i= 0; i < 1000; i++) {
  28.             results.remove(i);
  29.         }
  30.         System.out.println(“ —- ” + Thread.currentThread().getName()  + ”     ” + results.get(0));
  31.         return results.get(1);
  32.     }
  33.     public static void main(String[] args) throws InterruptedException, ExecutionException {
  34.         try {
  35.             for (int i = 0; i < 2000; i++) {
  36.                     HashMapDead2LiveLock hashMapDeadLock  = new HashMapDead2LiveLock();
  37. //                  Future<Integer> future = threadPool.submit(hashMapDeadLock);
  38. //                  future.get();
  39.                     threadPool.submit(hashMapDeadLock);
  40.                 }
  41.         } catch (Exception e) {
  42.             e.printStackTrace();
  43.         } finally {
  44.             threadPool.shutdown();
  45.         }
  46.     }
  47. }

 

改成ConcurrentHashMap后,重新执行该程序,你会发现很快该程序就执行完了。