Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to calculate available memory in Java?

Tags:

java

memory

jvm

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?

like image 675
Frank Flannigan Avatar asked Jun 02 '11 21:06

Frank Flannigan


1 Answers

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?

like image 195
leebutts Avatar answered Oct 21 '22 04:10

leebutts