如何在代码中分析 JVM 内存?
我正在编写一个无法在 Eclipse 中测试的 servlet,我需要在服务器上运行。我想做内存分析并查明任何泄漏。所以,我想我需要编写可以告诉我当前内存使用情况的调试语句。有人可以向我指出关于如何执行此操作和/或 JDK 中的哪些类执行此操作的良好参考吗?
请注意,我无法使用“Eclipse MAT”。
I am writing a servlet that I can't test in Eclipse, I need to run on server. I want to do memory profiling and pinpoint any leaks. So, I think I need write debug statements that can tell me current memory usage. Can someone point me to good references on how to do this and/or which classes in the JDK do this ?
Note that I can't use the "Eclipse MAT".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不能使用jdk中内置的工具 jvisualvm?
Can't you use the built-in tool in the jdk jvisualvm?
JConsole来拯救你!
JConsole to rescue you!
分析应用程序内存并查找泄漏将是一项艰巨的任务,更不用说简单的调试语句会产生误导。如果您无法使用远程连接到进程的工具,请使用 hprof 在我看来是一个不错的选择。另外,请查看此处的故障排除文档。
但我仍然认为如果可能的话,如果您尝试在本地执行相同的操作(即修复泄漏)会更好。
Profiling application memory and hunting down leaks would be a difficult task, not to mention misleading with simple debug statements. If you can't use a tool which remotely connects to your process, using hprof would be a good bet IMO. Also, have a look at the troubleshooting documentation here.
But I still think it would be better if you tried to do the same locally (i.e. fixing leaks) if possible.
这很可能不会对您有太大帮助,因为垃圾收集器使得仅通过查看计数就很难找到内存泄漏(您并不真正知道 gc 何时运行以及它实际收集的内容,它有时不收集一切可收藏的东西)。因此,您可能需要制作一些内存快照并对其进行分析,即查看哪些对象(或哪些类型的对象)没有被收集,从而创建了越来越多的实例。
为此,请查看建议的工具(JVisualVM、JConsole)。
如果您仍然想从程序内部获取内存使用信息,请尝试 java.lang.management 包;
That most likely won't help you much since the garbage collector makes it somewhat hard to find memory leaks by just looking at the counts (you don't really know when the gc runs and what it actually collects, it sometimes doesn't collect everything that is collectable). So you might need to make some memory snapshots and analyse them, i.e. see which objects (or which types of objects) are not collected and thus more and more instances are created.
For this, take a look at the suggested tools (JVisualVM, JConsole).
If you still want to get memory usage information from inside your program, try the classes in the java.lang.management package;
我想您和我一样更喜欢在代码中进行分析,而不是使用 JVisualVM 或 JConsole 等外部分析工具。
您可以使用名为 MemorySampler 的工具(由我写的)来自CoralBits,它会准确地告诉你在什么方面正在分配您的代码行内存。下面是一个示例:
为您提供以下输出:
现在,如果您转到 ConcurrentLinkedQueue 源代码的第 327 行,您将看到它在那里分配了一个 Node 实例。
免责声明:我是 CoralBits 的开发者之一。
I think you are like me who prefers to profile in code instead of using an external profiling tool like JVisualVM or JConsole.
You can use a tool called MemorySampler (written by me) from CoralBits that will tell you exactly in what line of your code memory is being allocated. Below an example:
Gives you the following output:
Now if you go to line 327 of the
ConcurrentLinkedQueue
source code, you will see that it allocates aNode
instance there.Disclaimer: I am one of the developers of CoralBits.