Measuring time spent on GC

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;
}

Leave a Comment