magicroomy
magicroomy

Reputation: 395

Java MemoryMXBean Used Memory bigger than Max

I got an interesting effect regarding runtime memory analysis with the MemoryMXBean. I would like to determine the Free memory in Heap together with NonHeap. So my code looks like this:

static MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
long fullused = mbean.getHeapMemoryUsage().getUsed() + mbean.getNonHeapMemoryUsage().getUsed();
long fullmax = mbean.getHeapMemoryUsage().getMax() + mbean.getNonHeapMemoryUsage().getMax();
long fullfree = fullmax - fullused;

Sometimes the result for fullFree is a negative value. How can that be? A race condition that some garbage collection was made after the calculation for the used mem? In my logs I see it quite often so I doubt the race condition theory. Any other thoughts here?

Upvotes: 1

Views: 637

Answers (1)

commit-man
commit-man

Reputation: 376

Max for NonHeap can be -1. You can check that via jconsole for your application. In hotspot sources calculation of memory usage is done in jmm_GetMemoryUsage method. If one of non heap memory pools has undefined max size, than max size in entire non heap will be -1. Metaspace pool (without MaxMetaspaceSize command flag) has undefined max size

Upvotes: 2

Related Questions