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

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

问题描述

我一直想知道 Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory()Runtime.getRuntime().maxMemory() 是.

I've been wondering what the exact meaning of Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory(), and Runtime.getRuntime().maxMemory() is.

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

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

freeMemory()maxMemory() 怎么样?

推荐答案

根据API

totalMemory()

返回 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()ma​​xMemory().答案是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 需要更多内存,它将延迟向上分配到最大内存.如果您使用 -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天全站免登陆