Runtime.getRunTime.maxMemory为啥比Xmx指定的内存小

先贴一些程序代码

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;

public class MemoryDemo {
    static String mb(long s) {
        return String.format("%d (%.2f M)", s, (double) s / (1024 * 1024));
    }

    public static void main(String[] args) {
        System.out.println("Runtime max: " + mb(Runtime.getRuntime().maxMemory()));
        MemoryMXBean m = ManagementFactory.getMemoryMXBean();

        System.out.println("Non-heap: " + mb(m.getNonHeapMemoryUsage().getMax()));
        System.out.println("Heap: " + mb(m.getHeapMemoryUsage().getMax()));

        for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
            System.out.println("Pool: " + mp.getName() + " (type " + mp.getType() + ")" + " = " + mb(mp.getUsage().getMax()));
        }
    }
}

程序运行过程中,设定了其最大堆内存

-Xmx10m -Xms10m

程序输出

Runtime max: 10092544 (9.63 M)
Non-heap: 136314880 (130.00 M)
Heap: 10092544 (9.63 M)
Pool: Code Cache (type Non-heap memory) = 50331648 (48.00 M)
Pool: PS Eden Space (type Heap memory) = 2686976 (2.56 M)
Pool: PS Survivor Space (type Heap memory) = 393216 (0.38 M)
Pool: PS Old Gen (type Heap memory) = 7012352 (6.69 M)
Pool: PS Perm Gen (type Non-heap memory) = 85983232 (82.00 M)

问题是通过Runtime.getRunTime.maxMemory得到的内存比设置的10m内存要小,只有9.63M?如下。为什么?

Runtime max: 10092544 (9.63 M)

其实原因很简单,maxMemory是拿到的程序最大可以使用的内存,我们知道 ,Survivor有两个,但只有1个会用到,另一个一直闲置。所以这个值maxMemory是去掉一个Survivor空间的值。

maxMemory=Eden+Survivor+Old Gen
9.63 M=2.56 M+0.38 M+6.69 M

以上文章参考自:

https://stackoverflow.com/questions/23701207/why-do-xmx-and-runtime-maxmemory-not-agree?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

文章为作者原创文章,如果对您有帮助,欢迎打赏!这里写图片描述这里写图片描述

猜你喜欢

转载自blog.csdn.net/wisgood/article/details/79850093