Notifying when reaching 80% of heap usage

Viewed 139

I have an internal cache which is held on the heap. I would like to notify when the heap is 80% utilised (after gc collection) so that I can arrange for the heap size to be increased (or some other action)

I'm taking a look at: https://docs.oracle.com/javase/7/docs/api/java/lang/management/MemoryMXBean.html, specifically: https://docs.oracle.com/javase/7/docs/api/java/lang/management/MemoryNotificationInfo.html#MEMORY_COLLECTION_THRESHOLD_EXCEEDED

It looks like I can set the threshold here: https://docs.oracle.com/javase/7/docs/api/java/lang/management/MemoryPoolMXBean.html#setCollectionUsageThreshold(long), however I'm unsure if this will have any undesired affects.

What is the best way to achieve what I am after?

1 Answers

You can take a look at how Hive does it in HeapMemoryMonitor class which calls MemoryPoolMXBean.setUsageThreshold() method after multiple checks are done.

If you want to set threshold to 80% you should calculate the value as:

MemoryPoolMXBean pool = ... 
pool.setUsageThreshold((long) Math.floor(pool.getUsage().getMax() * 0.8));
Related