你能用 Java 获得基本的 GC 统计数据吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/466878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you get basic GC stats in Java?
提问by Lawrence Dol
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.
我想让一些长时间运行的服务器应用程序定期输出 Java 中的一般 GC 性能数字,例如 Runtime.freeMemory() 等的 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.
我们在客户机器上运行的系统怀疑错误配置的内存池会导致过度的 GC 频率和长度 - 我认为通常定期报告基本 GC 活动会很好。
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.
编辑:我特别想在运行时将此数据输出到系统日志(控制台);这不是我想要连接到 JVM 的东西,就像使用 JConsole 或 JVisualVM 一样。
Edit2: The MX bean looks like what I want - does anyone have a working code example which obtains one of these?
Edit2: MX bean 看起来像我想要的 - 有没有人有一个工作代码示例可以获得其中之一?
采纳答案by Greg Case
Here's an example using GarbageCollectorMXBean
to print out GC stats. Presumably you would call this method periodically, e.g. scheduling using a ScheduledExecutorService
.
这是一个GarbageCollectorMXBean
用于打印 GC 统计信息的示例。大概您会定期调用此方法,例如使用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);
}
回答by Michael Myers
Try -XX:-PrintGC
and -XX:-PrintGCDetails
; see VM Debugging Options.
尝试-XX:-PrintGC
和-XX:-PrintGCDetails
; 请参阅VM 调试选项。
回答by Ran Biron
回答by Fortyrunner
Slightly off topic but you can hook up VisualVM and JConsole to running applications and see useful stats.
稍微偏离主题,但您可以将 VisualVM 和 JConsole 连接到运行应用程序并查看有用的统计信息。