jcmd工具使用

2016年11月29日

jcmd 简介

jcmd 是一个 JVM 自带的诊断工具,可发送诊断命令请求到一个正在运行的JVM.

使用

第一步:使用 jcmd 获取当前机器所有的正在运行的JVM列表

jaky@jaky-ProBook:~$ jcmd

6554 sun.tools.jcmd.JCmd

5541 org.jetbrains.idea.maven.server.RemoteMavenServer

5235 com.intellij.idea.Main

第二步:使用 jcmd [pid] help 获取指定JVM进程可执行的所有诊断命令

jaky@jaky-ProBook:~$ jcmd 5541 help

5541:

The following commands are available:

VM.native_memory

ManagementAgent.stop

ManagementAgent.start_local

ManagementAgent.start

GC.rotate_log

Thread.print

GC.class_stats

GC.class_histogram

GC.heap_dump

GC.run_finalization

GC.run

VM.uptime

VM.flags

VM.system_properties

VM.command_line

VM.version

help

For more information about a specific command use ‘help ’.

第三步: 直接看能执行的诊断命令的名称其实也基本能猜出来它的作用了, 更多的命令执行信息可通过 help <command> 来获取. 例如我想要查看线程信息相关的诊断命令Thread.print的使用,可通过 jcmd [pid] help <command>来查看

jaky@jaky-ProBook:~$ jcmd 5541 help Thread.print

5541:

Thread.print

Print all threads with stacktraces.

Impact: Medium: Depends on the number of threads.

Permission: java.lang.management.ManagementPermission(monitor)

Syntax : Thread.print [options]

Options: (options must be specified using the or = syntax)

-l : [optional] print java.util.concurrent locks (BOOLEAN, false)

可以看到这个命令可以打印所有线程的栈信息,执行这个命令对JVM的影响程度为中等(依赖于线程数量),可选参数有 -l (用来打印出每个线程使用的锁的情况)

参考

http://www.rowkey.me/blog/2016/11/16/java-trouble-shooting/

后续

这个命令只能查看当前登陆用户权限下创建的jvm实例。悲伤~~~~

The jcmd utility is used to send diagnostic command requests to the JVM, where these requests are useful for controlling Java Flight Recordings, troubleshoot, and diagnose JVM and Java Applications. It must be used on the same machine where the JVM is running, and have the same effective user and group identifiers that were used to launch the JVM.

http://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr006.html