Search code examples
javagarbage-collectionjmx

Determining GC type via GarbageCollectorMXBean


I was reading this excellent answer on grabbing Java garbage collection activity info and noticed that the GarbageCollectorMXBean doesn't have any data about what type of collection it was (Minor, Major, Full, etc.).

I'm wondering: is it possible to figure out (from Java code) whether a particular GC was minor, major or full?


Solution

  • Printing periodic GC stats from the GarbageCollectorMXBean's summary stats won't give you that type of information. If you are using Java 1.7+, you can subscribe to JMX notifications from each GarbageCollectorMXBean instance and you'll get a notification for every GC event which will give you a bit more detail on each individual event. The notification's UserData will contain an instance of the type GarbageCollectionNotificationInfo. The attribute GcAction will tell you if it was major or minor, and GcCause will tell you the GC event cause.

    Note that this references com.sun packages and assumes a HotSpot JVM. You can avoid referencing the com.sun packages in your code using pure JMX and OpenType inference, but be cautious about assuming this will work across all Java 1.7 JVMs.