你能在 Java 中获得基本的 GC 统计信息吗?
我想让一些长时间运行的服务器应用程序定期输出 Java 中的一般 GC 性能数字,比如 Runtime.freeMemory() 等 GC 等值.比如完成的周期数、平均时间等.
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.
我们的系统在客户机器上运行,怀疑配置错误的内存池会导致过多的 GC 频率和长度 - 我认为定期报告基本 GC 活动通常是好的.
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?
我特别想在运行时将此数据输出到系统日志(控制台);这不是我想连接到 JVM 的东西,就像 JConsole 或 JVisualVM 一样.
Edit2:MX bean 看起来像我想要的 - 有没有人有一个获得其中之一的工作代码示例?
The MX bean looks like what I want - does anyone have a working code example which obtains one of these?
推荐答案
这是一个使用 GarbageCollectorMXBean
打印出 GC 统计信息.大概您会定期调用此方法,例如使用 ScheduledExecutorService 进行调度
.
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);
}
相关文章