我试图计算出我的
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?