常用命令
2.1 jps
查看进程
The jps command lists the instrumented Java HotSpot VMs on the target system. The command is limited to reporting information on JVMs for which it has the access permissions.
2.2 jinfo
- 实时查看和调整JVM参数
The jinfo command prints Java configuration information for a specified Java process or core file or a remote debug server. The configuration information includes Java system properties and Java Virtual Machine (JVM) command-line flags.
- 查看
格式:jinfo -flag 如:jinfo -flag UserG1GC 126492
- 修改
只有被标记为manageable的参数才可以使用jinfo实时修改
格式: 1. jinfo -flag [+/-] 2. jinfo -flag = 如 jinfo -flag HeapDumpPath=log/heap.hprof 126492
2.3 jstat
- 查看类装载信息
jstat -class PID 1000 10 查看某个java进程的类装载信息,每1000毫秒输出一次,共输出10 次
- 查看垃圾收集信息
jstat -gc PID 1000 10
2.4 jstack
- 查看线程堆栈信息
jstack PID
- 排查死锁案例
1. 死锁代码
public class DeadLockDemo implements Runnable { boolean flag; public DeadLockDemo(boolean flag) { this.flag = flag; } @Override public void run() { if (flag) { while (true) { synchronized (MyLock.lock1) { System.out.println(Thread.currentThread().getName() + ": 获得lock1"); synchronized (MyLock.lock2) { System.out.println(Thread.currentThread().getName() + ": 获得lock2"); } } } } else { while (true) { synchronized (MyLock.lock2) { System.out.println(Thread.currentThread().getName() + ": 获得lock1"); synchronized (MyLock.lock1) { System.out.println(Thread.currentThread().getName() + ": 获得lock2"); } } } } } public static void main(String[] args) { Thread thread1 = new Thread(new DeadLockDemo(true), "线程1"); Thread thread2 = new Thread(new DeadLockDemo(false), "线程2"); thread1.start(); thread2.start(); } } class MyLock { public static final Object lock1 = new Object(); public static final Object lock2 = new Object(); }
- 运行结果*
3. jstack分析
Found one Java-level deadlock: ============================= "线程2": waiting to lock monitor 0x000000001c5db238 (object 0x000000076bc16bc0, a java.lang.Object), which is held by "线程1" "线程1": waiting to lock monitor 0x000000001c5ddac8 (object 0x000000076bc16bd0, a java.lang.Object), which is held by "线程2" Java stack information for the threads listed above: =================================================== "线程2": at DeadLockDemo.run(DeadLockDemo.java:27) - waiting to lock <0x000000076bc16bc0> (a java.lang.Object) - locked <0x000000076bc16bd0> (a java.lang.Object) at java.lang.Thread.run(Thread.java:748) "线程1": at DeadLockDemo.run(DeadLockDemo.java:18) - waiting to lock <0x000000076bc16bd0> (a java.lang.Object) - locked <0x000000076bc16bc0> (a java.lang.Object) at java.lang.Thread.run(Thread.java:748) Found 1 deadlock.
2.5 jmap
- 生成堆转储快照
The jmap command prints shared object memory maps or heap memory details of a specified process, core file, or remote debug server.
- 打印堆内存相关信息
jmap -heap PID
- dump出堆内存相关信息
jmap -dump:format=b,file=heap.hprof PID
- 当发生堆内存溢出时,自动生成dump文件
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=heap.hprof