Reputation: 33
Is there a way to get all objects instances from JVM memory and print its' toString() representation in file?
I need to do a shot of all my app's objects instances in moment of error.
I think dump is not what I looking for because it doesn't give me precise information about what instances were contained in memory at the moment, only statictics information.
Upvotes: 1
Views: 1270
Reputation: 878
What you are asking for is essentially called heap dump.
Heapdump is a snapshot of JVM memory in a given time, it contains info about all the objects.
To capture it you can do
jmap -dump:format=b,file=heap.bin <pid>
There are several tools that can analyze the file outputted. Good change is that your IDE can do it, that way you can view it in familiar interface.
More here https://dzone.com/articles/java-heap-dump-analyzer-1
To programatically trigger hepdump you can do something like this
public class HeapDumper {
private static final String HOTSPOT_BEAN_NAME =
"com.sun.management:type=HotSpotDiagnostic";
private static volatile HotSpotDiagnosticMXBean hotspotMBean;
static void dumpHeap(String fileName, boolean live) {
initHotspotMBean();
try {
hotspotMBean.dumpHeap(fileName, live);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
private static void initHotspotMBean() {
if (hotspotMBean == null) {
synchronized (HeapDumper.class) {
if (hotspotMBean == null) {
hotspotMBean = getHotspotMBean();
}
}
}
}
private static HotSpotDiagnosticMXBean getHotspotMBean() {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean bean =
ManagementFactory.newPlatformMXBeanProxy(server,
HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
return bean;
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
Triggering it like this
String fileName = "heap.bin";
boolean live = true; // only reachable object - true, all objects - false
dumpHeap(fileName, live);
Upvotes: 1