Reputation: 64026
I would like to have some long-running server applications periodically output general GC performance numbers in Java, something like the GC equivalent of Runtime.freeMemory(), etc. Something like number of cycles done, average time, etc.
We have systems running on customer machines where there is a suspicion that misconfigured memory pools are causing excessive GC frequency and length - it occurs to me that it would be good in general to periodically report the basic GC activity.
Is there any platform independent way to do this?
EDIT: I specifically want to output this data to the system log (the console), while running; this is not something I want to connect to the JVM for, as would be with JConsole or JVisualVM.
Edit2: The MX bean looks like what I want - does anyone have a working code example which obtains one of these?
Upvotes: 43
Views: 32470
Reputation: 191875
The JVM has a certain amount of garbage collector logging already built in, so depending on your requirements, you might not need a custom solution.
In Java 7, you can use -XX:-PrintGC
and -XX:-PrintGCDetails
; see VM Debugging Options.
In Java 8 to 10, use -XX:+PrintGC
and -XX:+PrintGCDetails
with a +
instead of a -
(source).
In Java 11 or later, the -XX options have been deprecated in favor of -Xlog:gc
. See Enabling Logging with the JVM Unified Logging Framework for more advanced options.
Upvotes: 12
Reputation: 12782
Slightly off topic but you can hook up VisualVM and JConsole to running applications and see useful stats.
Upvotes: 0
Reputation: 47421
Here's an example using GarbageCollectorMXBean
to print out GC stats. Presumably you would call this method periodically, e.g. scheduling using a ScheduledExecutorService
.
public void printGCStats() {
long totalGarbageCollections = 0;
long garbageCollectionTime = 0;
for(GarbageCollectorMXBean gc :
ManagementFactory.getGarbageCollectorMXBeans()) {
long count = gc.getCollectionCount();
if(count >= 0) {
totalGarbageCollections += count;
}
long time = gc.getCollectionTime();
if(time >= 0) {
garbageCollectionTime += time;
}
}
System.out.println("Total Garbage Collections: "
+ totalGarbageCollections);
System.out.println("Total Garbage Collection Time (ms): "
+ garbageCollectionTime);
}
Upvotes: 58