Friday, December 23, 2011

How to Get Garbage Collectors info in Java

There are many GC policy or algorithm you can use in your application, here is a good mapping between JVM configuration and GC collectors:
Note: Thanks for the Reference: http://www.kjkoster.org/zapcat/Zabbix_Java_Template.html

Here is a demo code on how to grab detail GC info of your application
BTW, I have added those capabilities to my customized Btrace source code already :)
 package cputime;  
 import java.lang.management.*;  
 import java.util.HashSet;  
 import java.util.List; 
 
 public class GCInfo {  
   final static HashSet<String> YoungGenGCType = new HashSet<String>();  
   static{  
     YoungGenGCType.add("Copy");  
     YoungGenGCType.add("ParNew");  
     YoungGenGCType.add("PS Scavenge");  
     YoungGenGCType.add("G1 Young Generation");  
   }  
   final static HashSet<String> OldGenGCType = new HashSet<String>();  
   static{  
     OldGenGCType.add("MarkSweepCompact");  
     OldGenGCType.add("PS MarkSweep");  
     OldGenGCType.add("ConcurrentMarkSweep");  
     OldGenGCType.add("G1 Old Generation");  
   }  
   public static void main(String[] args) throws InterruptedException{  
     List<GarbageCollectorMXBean> gcTypes = ManagementFactory.getGarbageCollectorMXBeans();  
       for (int i=0; i<gcTypes.size();i++){  
       System.gc();  
       if(YoungGenGCType.contains(gcTypes.get(i).getName()))  
       {  
         System.out.println("Minor GC: " + gcTypes.get(i).getName());  
         System.out.println("Minor GC Total Count:" + gcTypes.get(i).getCollectionCount());  
         System.out.println("Minor GC Total Time:" + gcTypes.get(i).getCollectionTime());  
       }  
       else{  
         System.out.println("Full GC: " + gcTypes.get(i).getName());  
         System.out.println("Full GC Total Count:" + gcTypes.get(i).getCollectionCount());  
         System.out.println("Full GC Total Time:" + gcTypes.get(i).getCollectionTime());  
       }  
     }  
   }  
 }  

No comments:

Post a Comment