話說,當軟體過了開發衝刺的高峰後,接下來就可以開始進行 JVM tuning 的動作了,而這時就會用到一些工具來觀察 JVM 運行的狀況。 基本上還是推薦好操作,好上手的工具來使用,例如:VisualVMProfiler或至少用個 JConsole

但有時,天不從人願,就是會遇到只有 console 的情況… 這時就只好用 JDK 內建的 command-line 工具來觀察 JVM 了!

1. jps 查看目前系統上運行的JVM的 Process 資訊

我主要是用來看觀察目標的 PID,以供後續使用,僅此而已。但下面講到的 jcmd 也有這樣的功能,所以就更少用到了。

  • jps <argument>
  • -l 條列各個JVM啟動點 main 的完整 package 資訊

2. jcmd 觀察 JVM 設定/資源和 thread 使用量

這個工具能觀察的東西就多了,例如 JVM 的系統參數、JVM 啟動參數、JVM 運行時間、載入的 Class 資訊、目前運行的 thread 資訊等等,都是在進行 tuning 時參考的資訊。

CommandsDescription
Thread.printPrint all threads with stacktraces. Commonly used
GC.rotate_logForce the GC log file to be rotated.
GC.class_statsProvide statistics about Java class meta data.
GC.class_histogramProvide statistics about the Java heap usage. Commonly used
GC.heap_dumpGenerate a HPROF format dump of the Java heap.
GC.run_finalizationCall java.lang.System.runFinalization().
GC.runCall java.lang.System.gc().
VM.uptimePrint VM uptime.
VM.flagsPrint VM flag options and their current values. Commonly used
VM.system_propertiesPrint VM flag options and their current values. Commonly used
VM.command_linePrint system properties. Commonly used
VM.versionPrint JVM version information.
VM.native_memoryPrint native memory usage
ManagementAgent.stopStop remote management agent.
ManagementAgent.start_localStart local management agent.
ManagementAgent.startStart remote management agent.

3. jstat 即時觀察 JVM GC的情況

最後,jstat 這項工具主要用於觀察 GC 的狀況,例如:各記憶體區塊的使用狀況、GC event 的次數、GC 花費的時間等等,透過這些資訊配合上一個 jcmd 就更容易找出 JVM 的 bottleneck。

OptionDescription
-classClass loader statistics. Commonly used
-compilerJava HotSpot VM Just-in-Time compiler statistics.
-gcGarbage-collected heap statistics.
-gccapacityMemory pool generation and space capacities.
-gccauseDisplays the summary of garbage collection statistics, includes the causes of the last garbage collection event and (when applicable) the current garbage collection event.
-gcmetacapacityMetaspace size statistics.
-gcnewNew generation statistics.
-gcnewcapacityNew generation space size statistics.
-gcoldOld generation and metaspace behavior statistics.
-gcoldcapacityOld generation size statistics.
-gcutilSummary of garbage collection statistics. Commonly used
-printcompilationJava HotSpot VM compiler method statistics.

下面以我常用的 -gcutil 來說明觀察 GC 時的參數 gcutil

  • S0: Survivor space 0 記憶體使用率
  • S1: Survivor space 1 記憶體使用率
  • E: Eden space 記憶體使用率
  • O: Old space 記憶體使用率
  • P: 記憶體使用率
  • YGC: young generation GC events 次數
  • YGCT: Young generation GC time
  • FGC: Full GC events 次數
  • FGCT: Full GC time in second since the JVM started
  • GCT: Total gc time in second since the JVM started

ref: