14

I am creating a scheduled executor to read the memory usage of the JVM. I have come across two ways to get memory statistics in a running JVM - Runtime & MemoryMXBean, with the following correspondence between their methods:

memoryMxBean.getHeapMemoryUsage().getUsed()      <=> runtime.totalMemory() - runtime.freeMemory()
memoryMxBean.getHeapMemoryUsage().getCommitted() <=> runtime.totalMemory()
memoryMxBean.getHeapMemoryUsage().getMax()       <=> runtime.maxMemory()

With the exception of the additional non-heap memory usage information provided by MemoryMXBean, are there any reasons why I should prefer it over Runtime, or vice-versa?

2 Answers 2

7

There are none. JMX bean can be accessed externally and is meant for management tools like hyperic ( or even nagios ) - It would delegate to Runtime anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Both ways return exactly the same value for the used memory.
0

If you're trying to opt for performance: Runtime.getRuntime().totalMemory()/freeMemory()/maxMemory() are inlined native calls, whereas MemoryMXBean.getHeapMemoryUsage() involves more indirection and object allocation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.