10

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?

giampaolo
  • 6,906
  • 5
  • 45
  • 73
Frank Flannigan
  • 1,339
  • 3
  • 16
  • 25
  • 1
    Your solution looks correct to me. – Adrian Jun 02 '11 at 21:56
  • I thought they were the same but now I see that the 2nd one just gives you (max - total). – trutheality Jun 02 '11 at 23:47
  • 1
    I think you should put part of your question as an answer, so that this could by filed as an answered question. [Should I answer my own questions](http://meta.stackexchange.com/questions/12513/should-i-not-answer-my-own-questions) – Jarekczek Sep 17 '12 at 12:39

1 Answers1

8

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?

Community
  • 1
  • 1
leebutts
  • 4,882
  • 1
  • 23
  • 25