Can you get basic GC stats in Java?

前端 未结 4 2000
不思量自难忘°
不思量自难忘° 2020-11-30 02:03

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

相关标签:
4条回答
  • 2020-11-30 02:44

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

    0 讨论(0)
  • 2020-11-30 02:57

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

    0 讨论(0)
  • 2020-11-30 02:58

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 03:01

    See GarbageCollectorMXBean.

    0 讨论(0)
提交回复
热议问题