gpt4 book ai didi

java - 在 Java 中计算可用内存的最佳方法是什么?

转载 作者:IT王子 更新时间:2023-10-28 23:33:27 26 4
gpt4 key购买 nike

我正在尝试计算我的 Java 程序可用的内存量。我有这个当前的实现:

long getAvailableMemory() {
Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long maxMemory = runtime.maxMemory();
long usedMemory = totalMemory - freeMemory;
long availableMemory = maxMemory - usedMemory;
return availableMemory;
}

对吗?有没有更简单/更准确的方法来计算这些信息?看了别人的代码后,我看到这样的东西略有不同:

long getAvailableMemory() {
long totalVmHeap = Runtime.getRuntime().totalMemory();
long freeVmHeap = Runtime.getRuntime().freeMemory();
long usedVmHeap = totalVmHeap - freeVmHeap;
long maxVmHeap = Runtime.getRuntime().maxMemory();
long availableVmHeap = maxVmHeap - usedVmHeap + freeVmHeap;
return availableVmHeap;
}

无论如何,获取这些信息的正确方法是什么?

最佳答案

您的解决方案对我来说是正确的(在下面评论以解释您正在计算的内容):

long getAvailableMemory() {
Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory(); // current heap allocated to the VM process
long freeMemory = runtime.freeMemory(); // out of the current heap, how much is free
long maxMemory = runtime.maxMemory(); // Max heap VM can use e.g. Xmx setting
long usedMemory = totalMemory - freeMemory; // how much of the current heap the VM is using
long availableMemory = maxMemory - usedMemory; // available memory i.e. Maximum heap size minus the current amount used
return availableMemory;
}

我不确定您的用例是什么,但您可能希望查看的堆内也有一些限制,例如 PermGen 大小:How do I programmatically find out my PermGen space usage?

关于java - 在 Java 中计算可用内存的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6220790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com