Search code examples
javamemoryjava-native-interfaceswig

Track native memory usage from Java?


Is there any way I can log native memory usage from Java, i.e., either native memory directly or the total memory the process is using (e.g., ask the OS)?

I'd like to run this on user's machines behind the scenes, so the NativeMemoryTracking command line tool isn't really the most appealing option. I already log free/max/total heap sizes.

Background: A user of my software reported an exception (below) and I have no idea why. My program does use SWIG'd native code, but it's a simple API, I don't think it has a memory leak, and wasn't on the stacktrace (or run immediately before the error). My log indicated there was plenty of heap space available when the error occurred. So I'm really at a loss for how to track this down.

java.lang.OutOfMemoryError: null
    at java.io.RandomAccessFile.writeBytes0(Native Method) ~[na:1.7.0_45]
    at java.io.RandomAccessFile.writeBytes(Unknown Source) ~[na:1.7.0_45]
    at java.io.RandomAccessFile.write(Unknown Source) ~[na:1.7.0_45]

The error occurred on Windows (7 or 10)(?) from within webstart, configured with these parameters:

<java href="http://java.sun.com/products/autodl/j2se" initial-heap-size="768m" java-vm-args="" max-heap-size="900m" version="1.7+"/>

Solution

  • I ended up using this code which asks the OS for RSS and Peak memory usage. It was straightforward for me to add since I already have a SWIG module set up. The code might not be threadsafe since I hit a random malloc exception when I was testing, meaning I'm not sure I want to keep it in there.

    I'm really surprised the JVM doesn't provide a way to do this. Please someone let me know if there's a way.