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

前端之家收集整理的这篇文章主要介绍了在Java中计算可用内存的最佳方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图计算出我的 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?

原文链接:https://www.f2er.com/java/124757.html

猜你在找的Java相关文章