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