views:

676

answers:

4

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?

+1  A: 

Try -XX:-PrintGC and -XX:-PrintGCDetails; see VM Debugging Options.

Michael Myers
Good idea; but too verbose to be on always. I want a periodic report, say every 5-60 minutes.
Software Monkey
IOW, I want the data so I can output under my own timetable.
Software Monkey
Oooh. That makes it tougher.
Michael Myers
Then i think you'd have to write something else to capture the output and reformat/reoutput it at your times.
John Gardner
+3  A: 

See GarbageCollectorMXBean.

Ran Biron
Thanks, by the way Ran; would have accepted this too, if I could accept two answers.
Software Monkey
+2  A: 

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);
}
Greg Case
That's perfect thanks Greg. I already have a periodic monitor that prints memory usage and optionally threads. This fits in nicely with that.
Software Monkey
PS: Can't vote for another 46 minutes; will return and upvote this then.
Software Monkey
A: 

Slightly off topic but you can hook up VisualVM and JConsole to running applications and see useful stats.

Fortyrunner
Refer to the bolded edit I wrote 13 hours before this answer was posted.
Software Monkey
Apologies for that - sometimes you can't see the wood for the trees.
Fortyrunner