Measuring time spent on GC in JVM

Michael picture Michael · Dec 17, 2012 · Viewed 15.8k times · Source

Suppose I am testing a Java server application. I know how much time it takes to finish the test. Now I'd like to know how much was spent on GC during that test. How can I do it?

Answer

Steve McLeod picture Steve McLeod · Dec 17, 2012

I guess that when GC (Garbage Collector) is working the application stops and resumes when GC finishes

I don't think that is a safe assumption. Are you sure the garbage collector is not working in parallel with your application code?

To measure the time spent in collecting garbage you can query the Garbage Collector MXBean.

Try this:

public static void main(String[] args)  {
    System.out.println("collectionTime = " + getGarbageCollectionTime());
}

private static long getGarbageCollectionTime() {
    long collectionTime = 0;
    for (GarbageCollectorMXBean garbageCollectorMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
        collectionTime += garbageCollectorMXBean.getCollectionTime();
    }
    return collectionTime;
}