Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

garbage collection - Can you get basic GC stats in Java?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...