tags:

views:

164

answers:

3

I am trying to detect memeory leak in my java codes with java profilers VisualVM. I want to report the maximum memory usage before and after I fix a memory leak. While running VisualVM or other java profilers, is there anyway to find out the peak of the memeory usage? Thanks!

A: 

You can call Runtime.maxMemory() for how much memory the VM had allocated (this usually doesn't shrink). If you do this in a shutdown hook, then the value should be pretty accurate.

Aaron Digulla
+2  A: 

You can do this with VisualVM. First, install the VisualVM-MBeans plugin, and restart VisualVM. After that on the new MBeans tab choose java.lang.Memory.HeapMemoryUsage. The max value will give you the maximal allocated memory.

Update:

I double-checked it, and HeapMemoryUsage.max isn't the peak heap usage indeed. Fortunately, there are per-generation peak usage statistics in java.lang.MemoryPool.<Generation>.PeakUsage.used. To verify it, I wrote a small program that allocates some memory, and PeakUsage.max for Eden Space plus Old Gen plus Survivor Space gives the desired peak heap usage.

So here's what you can do:

  • You can use these per-generation statistics. You can also write some small tool that computes and prints the sum of the peak use of each generation for a given process via JMX.

  • If you only need some approximation, you can check the Monitor tab in VisualVM, the purple area on the Heap chart is Used Heap, so you can get some idea about the peak usage as well.

  • If you need this to eliminate a memory leak, what you really need is the long-time memory allocation pattern, and again, that is available on the Heap chart in VisualVM. This is a good start.

candiru
Hi, I checked java.lang.Memory.HeapMemoryUsage, it only tells you the max heap memory allocated, not the peak of the memory usage from the start to the end of running your application
flyingfromchina
Oh, you're right, sorry. Check my updated answer, I hope this helps.
candiru
A: 

Use jmap or -XX:+HeapDumpOnCtrlBreak to accurately measure the memory used in your application at any given time. Both of these mechanisms trigger a GC when the memory snapshot is taken, so its more accurately reflects the contents and size of the heap. You can use jhat to open the heap dump.

Amir Afghani