views:

576

answers:

2

I need a way to request a heap dump from within the application.

Rationale: When I encounter a specific error condition, I'd like to dump heap, so that I can see what is holding on to the memory.

But I would like to automate this (For example, when I detect that some specific condition has occurred. Or when a watchdog doesn't gets its pings anymore. When some test fails). Thus I need a way to dump the heap from within the application itself. I can't seem to find it with the MX beans stuff. Although the MX Beans can give very nice stack traces with monitor and "ownable synchronizer" info, deadlock and contention info, I can't seem to find a way to request a heap dump. Are there any such way? Or by some indirect means, for example how does these JVisualVM things do it? And one can tell the JVM to dump core on OutOfMemoryExceptions..?

+2  A: 

What about using the VM option -XX:+HeapDumpOnOutOfMemoryError to tell the HotSpot VM to generate a heap dump when it runs out of memory?

Pascal Thivent
+1: the only "specific error condition" where the OP can reasonably know that something is holding onto memory, is an OutOfMemoryError; in which case dumping heap at this point gives the heap dump desired.
Andrzej Doyle
@Andrzej: Why would that be the the only "reasonable" error condition? There are plenty of ways to realize what the memory situation of a VM is from within, e.g. WeakReference, checking the memory counters of Runtime and MX beans etc (before and after System.gc()) - boatloads. JProfiler rocks, but I wanted a programmatic, non-JProfiler solution. Here's another guy whose problem I can relate to: http://www.velocityreviews.com/forums/t275440-dump-complete-java-vm-state-as-core-dump-not-via-os-possible.html I bet he would have loved the solution that I was given here!
stolsvik
+5  A: 

If it's not enough to dump heap on OutOfMemoryError, there's a HotSpot-dependent way of programmatically dumping heap from Java applications, if that's OK.

gustafc
Awesome, just what I was looking for, Thanks! I find it amazing that I didn't find that blog post during my googling. Under sun.management, there are apparently lots of fun!
stolsvik
One more comment, though (back to the ideas posted in the OP): From your "dump heap on OutOfMemoryError" link, I can read: "The built-in heap dumper can also be used to take a snapshot of the heap at other times. This is done using the using the jmap command line utility or jconsole monitoring and management console.". Those tools then probably use the proprietary MXBean that the second link refers to? I find it strange that the standard MX-beans don't have this dumpHeap(fileName, live) method.
stolsvik
Sort of annoying, yes, but I would guess that were it a standard functionality, the heap dump format should be standardized too. At the very least, I imagine that'd be a lot of work, and it could possibly limit the freedom vendors have in their VM implementations.
gustafc