Best way to profile memory usage in a Java application?

Matt picture Matt · Apr 16, 2009 · Viewed 27.6k times · Source

I realize that similar questions have been asked about this before here on SO, but let me describe exactly what I need to do:

I have a set of tests which run a command line java application and I'd like to add memory profiling to them. One option I see would be to add code (possibly using 3rd party tools/libraries) to my application that would provide a memory snapshot. Another option would be to use a third party tool which manages/instruments my application and the JVM for me (and ideally does not require me to change my code). I'm thinking of something like Valgrind but for Java. Also open source if at all possible.

What I'd really like to do is set up the memory tests so that my memory usage is being monitored at regular intervals, let's say every second, and dumped to a text file. That way I'd be able to see if the memory usage oscillates/increases/decreases over time. I'll also be able to calculate the max and min peaks.

Has anyone here done anything like this?

Thanks in advance.

Answer

Peter D picture Peter D · Apr 16, 2009

With something like JProfiler all you need to do is add certain parameters to the JVM. It uses JVMTI.

I think you should be reading up on profilers and exactly what they can do for you. I also suggest reading up on JVMTI.

The JVMTM Tool Interface (JVM TI) is a new native programming interface for use by tools. It provides both a way to inspect the state and to control the execution of applications running in the Java virtual machine (JVM). JVM TI supports the full breadth of tools that need access to JVM state, including but not limited to: profiling, debugging, monitoring, thread analysis, and coverage analysis tools.

Note: JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI). JVMPI and JVMDI will be removed in the next major release of J2SETM.