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

时间:2011-06-02 21:49:05

标签: java memory jvm

我正在尝试计算我的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;
}

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

1 个答案:

答案 0 :(得分:8)

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

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?