Search code examples
javaclassgarbage-collectionhistogram

How can I get the GC class histogram programmatically


I would like to get the same result of the follow command programmatically:

jcmd <pid> GC.class_histogram | grep 'sun.util'

 728:            27           2592  sun.util.calendar.Gregorian$Date
 800:            44           2112  sun.util.locale.LocaleObjectCache$CacheEntry
 816:            36           2016  sun.util.calendar.ZoneInfo
1169:            22            880  sun.util.locale.BaseLocale$Key

...

I already searched for many answers, but none of the found is clear and do what I want, is there any way to do that?


Solution

  • The follow code shows the same result:

    import javax.management.MBeanException;
    import javax.management.ReflectionException;
    
    import com.sun.management.DiagnosticCommandMBean;
    
    import sun.management.ManagementFactoryHelper;
    
    @SuppressWarnings("restriction")
    public class ClassHistogram {
    
        public static void main(String[] args) throws MBeanException, ReflectionException {
            DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
    
            String[] emptyStringArgs = {};
            Object[] dcmdArgs = { emptyStringArgs };
            String[] signature = { String[].class.getName() };
            System.out.println(dcmd.invoke("gcClassHistogram", dcmdArgs, signature));
        }
    
    }
    

    Reference from the available commands: https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr006.html