What's the best way to calculate available memory in Java?
I am trying to calculate how much memory is available to my Java program. I have this current implementation:
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;
}
Is that right? Is there an easier/more accurate way of calculating this information? After looking at someone else code, I saw something like this which is slightly different:
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;
}
Anyway, what's the right way to 开发者_开发知识库get at this information?
You solution looks correct to me (commented below to explain what you're calculating):
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;
}
I'm not sure what your use case is but there are also limits within the heap you might want to look at like PermGen size: How do I programmatically find out my PermGen space usage?
精彩评论