You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询totalMemory()与maxMemory()的区别:VM堆大小与堆大小限制获取

Difference between totalMemory() and maxMemory() in Java

Hey there! Let me clear up the confusion between these two Runtime methods—they’re related but measure very different things:

What does maxMemory() return?

This is the absolute maximum amount of heap memory the JVM is allowed to use. It’s set by the -Xmx command-line parameter when you start your Java program (e.g., -Xmx2g means the JVM can’t use more than 2 gigabytes of heap).

Once your program tries to allocate memory that would push the total used heap beyond this limit, you’ll get an OutOfMemoryError. This value stays fixed for the lifetime of the JVM (unless you’re using a JVM that supports dynamic heap resizing, which is less common).

What does totalMemory() return?

This is the amount of heap memory the JVM has already requested from the operating system. The JVM doesn’t grab all the maxMemory upfront—it asks the OS for memory incrementally as your program needs it.

For example, if you set -Xms512m (initial heap size) and -Xmx2g, totalMemory() will start around 512MB. As your program creates more objects and fills up that space, the JVM will request more memory from the OS, so totalMemory() will grow—until it hits the maxMemory() limit.

Also, note that when garbage collection runs and frees up memory, the JVM might not immediately give that unused memory back to the OS. So totalMemory() represents the total heap the JVM currently holds, not just what’s actively being used.

Quick bonus: freeMemory()

If you’re curious about actual used memory, you can calculate it as totalMemory() - freeMemory(). freeMemory() gives you the amount of space within the currently allocated totalMemory that’s not being used by objects.


内容的提问来源于stack exchange,提问作者Mani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:12:57