跟踪 java profiler 中的最大内存使用情况
我正在尝试使用 java 分析器 VisualVM 检测 java 代码中的内存泄漏。我想报告修复内存泄漏之前和之后的最大内存使用情况。在运行 VisualVM 或其他 java 分析器时,是否有办法找出内存使用的峰值?谢谢!
I am trying to detect memeory leak in my java codes with java profilers VisualVM. I want to report the maximum memory usage before and after I fix a memory leak. While running VisualVM or other java profilers, is there anyway to find out the peak of the memeory usage? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 VisualVM 来完成此操作。首先,安装 VisualVM-MBeans 插件,然后重新启动 VisualVM。之后,在新的 MBeans 选项卡上选择 java.lang.Memory.HeapMemoryUsage。最大值将为您提供最大分配内存。更新:
我仔细检查了它,HeapMemoryUsage.max确实不是峰值堆使用量。幸运的是,java.lang.MemoryPool..PeakUsage.used 中有每代的峰值使用统计信息。为了验证这一点,我编写了一个分配一些内存的小程序,Eden Space 加上 Old Gen 加上 Survivor Space 的 PeakUsage.max 给出了所需的峰值堆使用情况。
因此,您可以执行以下操作:
您可以使用这些每代统计信息。您还可以编写一些小工具,通过 JMX 计算并打印给定进程的每一代的峰值使用总和。
如果您需要它来消除内存泄漏,那么您真正需要的是长时间内存分配模式,并且可以在 VisualVM 的堆图表中找到该模式。 这是一个好的开始.
You can do this with VisualVM. First, install the VisualVM-MBeans plugin, and restart VisualVM. After that on the new MBeans tab choose java.lang.Memory.HeapMemoryUsage. The max value will give you the maximal allocated memory.Update:
I double-checked it, and HeapMemoryUsage.max isn't the peak heap usage indeed. Fortunately, there are per-generation peak usage statistics in java.lang.MemoryPool.<Generation>.PeakUsage.used. To verify it, I wrote a small program that allocates some memory, and PeakUsage.max for Eden Space plus Old Gen plus Survivor Space gives the desired peak heap usage.
So here's what you can do:
You can use these per-generation statistics. You can also write some small tool that computes and prints the sum of the peak use of each generation for a given process via JMX.
If you only need some approximation, you can check the Monitor tab in VisualVM, the purple area on the Heap chart is Used Heap, so you can get some idea about the peak usage as well.
If you need this to eliminate a memory leak, what you really need is the long-time memory allocation pattern, and again, that is available on the Heap chart in VisualVM. This is a good start.
您可以调用 Runtime.maxMemory() 来获取虚拟机分配的内存量(通常不会收缩)。如果您在关闭挂钩中执行此操作,则该值应该非常准确。
You can call
Runtime.maxMemory()
for how much memory the VM had allocated (this usually doesn't shrink). If you do this in a shutdown hook, then the value should be pretty accurate.使用 jmap 或 -XX:+HeapDumpOnCtrlBreak 可以准确测量应用程序在任何给定时间使用的内存。这两种机制在拍摄内存快照时都会触发GC,因此更准确地反映堆的内容和大小。您可以使用 jhat 打开堆倾倒。
Use jmap or -XX:+HeapDumpOnCtrlBreak to accurately measure the memory used in your application at any given time. Both of these mechanisms trigger a GC when the memory snapshot is taken, so its more accurately reflects the contents and size of the heap. You can use jhat to open the heap dump.