什么是Runtime.getRuntime().totalMemory()和freeMemory()? [英] What are Runtime.getRuntime().totalMemory() and freeMemory()?

查看:196
本文介绍了什么是Runtime.getRuntime().totalMemory()和freeMemory()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道 Runtime.getRuntime().totalMemory()我的理解是,Runtime.getRuntime().totalMemory()返回我的进程正在使用的总内存.那是对的吗?

My understanding is, Runtime.getRuntime().totalMemory() returns the total memory my process is using. Is that correct?

freeMemory()maxMemory()怎么样?

推荐答案

根据返回Java虚拟机中的内存总量.此方法返回的值可能会随时间变化,具体取决于主机环境. 请注意,保存任何给定类型的对象所需的内存量可能取决于实现.

Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

maxMemory()

返回Java虚拟机将尝试使用的最大内存量.如果没有固有限制,则将返回Long.MAX_VALUE值.

Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

freeMemory()

返回Java虚拟机中的可用内存量.调用gc方法可能会增加freeMemory返回的值.

Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.

关于您的问题,maxMemory()返回-Xmx值.

In reference to your question, maxMemory() returns the -Xmx value.

您可能想知道为什么会有 totalMemory() maxMemory().答案是JVM延迟分配内存.可以这样说来启动Java进程:

You may be wondering why there is a totalMemory() AND a maxMemory(). The answer is that the JVM allocates memory lazily. Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

您的进程以64mb的内存开始,并且当需要更多内存(最大1024m)时,它将分配内存. totalMemory()对应于JVM用于Foo的当前的内存量.如果JVM需要更多内存,则会将 up 分配给最大内存.如果使用-Xms1024m -Xmx1024m运行,则从totalMemory()maxMemory()获得的值将相等.

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory() corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.

此外,如果要准确计算已用的内存量,请执行以下计算:

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();

这篇关于什么是Runtime.getRuntime().totalMemory()和freeMemory()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆