Java JDK目录下的jmap和jhat东西的运用方法

Suppose you have a running Java process and you would like to inspect its running status, for example how many object instance are created or memory consumption status, you can use some standard tool provided by JDK.
This blog is written based on JDK 1.8.
The sample code I am using to simulate a endless running process:

package jmap;
class Tool{
private int count = 0;
public void Run() throws InterruptedException{
while(true){
System.out.println("Hello: " + this.count++);
Thread.sleep(5000);
}
}
}
public class JMapTest {
public static void main(String[] args) throws InterruptedException {
Tool tool = new Tool();
tool.Run();
}
}

(1) First get process id found in task manager: 15392

Java JDK目录下的jmap和jhat东西的运用方法

(2) use command line
jmap -dump:format=b,file=c:tempheapstatus.bin 15392
jmap is a standard tool provided by JDK in this folder in my laptop:

Java JDK目录下的jmap和jhat东西的运用方法

heap bin file is generated now:

Java JDK目录下的jmap和jhat东西的运用方法

(3) Use another tool jhat to parse the bin file:
jhat c:tempheapstatus.bin

Java JDK目录下的jmap和jhat东西的运用方法

Then access localhost:7000 in browser:

Java JDK目录下的jmap和jhat东西的运用方法

Click hyperlink class jmap.Tool, now I can find out that the instance of my tool class @0x7166babd8 has member attribute count with value 49.

Java JDK目录下的jmap和jhat东西的运用方法

(4) There is a plugin in Eclipse MAT – Memory Analyzer Tool which can achieve the same.
Once plugin is installed, you can make them visible in “Show View”:

Java JDK目录下的jmap和jhat东西的运用方法

Drag your bin file into the view and the heap file will be parsed automatically.
Click “Find object by address”:
Java JDK目录下的jmap和jhat东西的运用方法

Type address of object instance you want to inspect:

Java JDK目录下的jmap和jhat东西的运用方法

You can get the same result as you get previously in localhost:7000

Java JDK目录下的jmap和jhat东西的运用方法

本文来自云栖社区合作伙伴“汪子熙”,了解相关信息能够重视微信大众号"汪子熙"。