How to monitor memory after major garbage collecti

2019-07-23 09:42发布

问题:

Many monitoring tools, like the otherwise phantastic JavaMelody, just monitor the current memory usage. If you want to check for memory leaks or impending out of memory situations, this is not particularily helpful, if you have an application that generates loads of garbage which gets collected immediately. Not perfect, but IMHO much more interesting, would it be to monitor the memory usage immediately after a major garbage collection. If that's high, a crash is looming over you.

So: can you find out the memory usage immediately after the last major garbage collection - either from Java code or via JMX? I know there are some tools like VisualVM which do this (which is no option for production use), and it can be written in the garbage collection log, but I'm looking for a more straightforward solution than parsing the garbage collection logfile. :-) To be clear: I'm looking for something that can easily be used in any application in production, not any expensive tool for debugging.

In case that matters: JDK 7 with -XX:+UseConcMarkSweepGC , but I am interested in general answers, too.

回答1:

Information about memory available right after gc (youg or old) is available via JMX.

Garbage collector MBean has attribute LastGcInfo which is composite data object including information about memory pool sizes before and after GC.

In addition, starting with Java 7 JMX notification subscription could be used to receive GC events without polling.

You can find example of code working with GC MBean here.



回答2:

Probably 'Dynatrace' is an option... it's a very powerful monitoring tool (not only for memory). http://www.dynatrace.com/en/index.html



回答3:

A very crude way would be to monitor the minima of Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() for some time. At least that would not require you to know intimate details about memory pools, as monitoring LastGcInfo in Alexey Ragozin's answer does. This might require you to get notifications about garbage collections.