Search code examples
javajavabeansjmx

JMX to get live heap memory usage reports constant values


I have a program that monitors the heap memory usage of the JVM. From what I understand from the documentations, there is only one JVM in the system and we can use ManagementFactory.getMemoryBean() to get the MXbean of the JVM. But when I run this program repeatedly over time, I get constant values for heap memory used. I have a java program that creates objects and destroys them in a loop. When monitoring in JVisualVM, the live usage graph indicates that the heap memory usage is variable over time, and since it runs on the same JVM, shouldn't these values change as well?

Here is the snippet for obtaining the memory:

        MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage mem = memBean.getHeapMemoryUsage();

        long heapMax = mem.getMax();
        long heapCurrMax = mem.getInit();
        long heapUsed = mem.getUsed();
        long heapCommitted = mem.getCommitted();

Output for Used memory:

379771840
379771840
379771840
379771840
379771840
379771840
All taken 5 seconds apart.

Can someone tell me if what I'm doing is wrong or if what I have understood is wrong in the first place?


Solution

  • I don't know how, but the same code started working after repeated tries. Will post a detailed analysis after I do one.