在执行过程中,java 程序如何知道它使用了多少内存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/239202/
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
During execution, how can a java program tell how much memory it is using?
提问by Ron Tuffin
During execution, how can a java program tell how much memory it is using?
在执行过程中,java 程序如何知道它使用了多少内存?
I don't care how efficient it is!
我不在乎它的效率有多高!
回答by Jon Skeet
VonC's answer is an interactive solution - if you want to know programatically, you can use Runtime.totalMemory()to find out the total amount used by the JVM, and Runtime.freeMemory()to find out how much of that is still available (i.e. it's allocated tothe JVM, but not allocated withinthe JVM - new objects can use this memory).
VonC 的答案是一个交互式解决方案——如果你想以编程方式知道,你可以使用Runtime.totalMemory()来找出 JVM 使用的总量,并使用Runtime.freeMemory()来找出其中还有多少可用(即它已分配给JVM,但未在JVM内分配- 新对象可以使用此内存)。
These are instance methods - use Runtime.getRuntime()to first get the singleton instance.
这些是实例方法 - 使用Runtime.getRuntime()首先获取单例实例。
回答by VonC
If you are have a java1.6 somewhere and your program is running in java 1.4.2, 1.5 or 1.6, you can launch a visualVM session, connect to your application, and follow the memory (and much more)
如果您在某处有 java1.6 并且您的程序在 java 1.4.2、1.5或 1.6 中运行,您可以启动一个visualVM 会话,连接到您的应用程序,并跟踪内存(以及更多)


(The images are not displayed at the moment, so please refers to Monitoring an applicationfor an illustration.)
(图片暂时不显示,请参考监控应用中的说明。)
回答by mcjabberz
This won't be exact, but for a rough estimate, just subtract Runtime.getRuntime.freeMemory()from Runtime.getRuntime.totalMemory().
Do that at the beginning of the program to get an idea of the JVM'soverhead memory usage and at intervals latter on in the execution.
这会不会是准确的,但对于一个粗略的估计,只是减去Runtime.getRuntime.freeMemory()从Runtime.getRuntime.totalMemory()。在程序开始时执行此操作,以了解JVM's开销内存使用情况,并在执行后的间隔中执行此操作。
回答by anjanb
java.lang.Runtime.totalMemory() will give you the required info -- http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
java.lang.Runtime.totalMemory() 会给你所需的信息——http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html

