jcmd เป็น JVM diagnostic tool แบบ command-line ใช้รัน diagnostic commands ต่อ JVM ที่กำหนดบนเครื่อง local tool นี้รวมอยู่ใน JDK ตั้งแต่ Java 7 อยู่ที่ %java_home%\bin\jcmd.exe หากมี %java_home%\bin ใน PATH environment variable สามารถรัน jcmd -h เพื่อดู options ทั้งหมดได้
Help Output
C:\Users\User>jcmd -h
Usage: jcmd ...
or: jcmd -l
or: jcmd -h
command must be a valid jcmd command for the selected jvm.
Use the command "help" to see which commands are available.
If the pid is 0, commands will be sent to all Java processes.
The main class argument will be used to match (either partially or fully) the class used to start Java.
If no options are given, lists Java processes (same as -l).
PerfCounter.print display the counters exposed by this process
-f read and execute commands from the file
-l list JVM processes on the local machine
-h this help
ตัวอย่างโค้ดทดสอบ
public class JCmdToolTest {
public static void main(String args[]) {
Runtime runtime = Runtime.getRuntime();
System.out.println("Free memory: " + runtime.freeMemory());
System.out.println("Total memory: " + runtime.totalMemory());
try {
Thread.sleep(5000);
} catch(InterruptedException e) { }
}
}
ผลลัพธ์โปรแกรม
Free memory: 65454560
Total memory: 67108864
การใช้งานจริง
C:\Users\User>jcmd -l
6108 jdk.jcmd/sun.tools.jcmd.JCmd -l
คำสั่ง jcmd ที่นิยมใช้
| คำสั่ง | คำอธิบาย |
|---|---|
| jcmd |
แสดงคำสั่งที่รองรับสำหรับ PID นั้น |
| jcmd |
แสดง Java version |
| jcmd |
แสดง JVM flags |
| jcmd |
แสดงข้อมูล heap |
| jcmd |
บังคับรัน Garbage Collection |
| jcmd |
แสดง thread dump |
| jcmd |
แสดง system properties |
| jcmd |
แสดง command line ที่ใช้เริ่ม JVM |
| jcmd |
เริ่ม Java Flight Recording |
| jcmd |
หยุด Java Flight Recording |
ข้อดีของ jcmd
- Lightweight - ไม่ต้อง attach debugger เต็มรูปแบบ
- ทำงานกับ running JVM ได้โดยไม่หยุดโปรแกรม
- รองรับ diagnostic commands มากมาย
- ใช้สคริปต์อัตโนมัติได้ด้วย flag
-f