0

Suppose I have a JVM that is solely dedicate to run one program, how can I get the amount of RAM that is allocated to the JVM?

Let's say my computer has 4GB and I specify via JVM parameters that the max it should used is 2GB, then 2GB is the output that I should get.

Conversely, if I do not specify any parameters to the JVM, the output should be the default value, whatever it is.

1 Answers1

1
long maxMemory = Runtime.getRuntime().maxMemory();

That is the max amount of memory a JVM can allocate, measured in bytes.

See the following link to the details of that method: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#maxMemory()

Alejandro Goñi
  • 492
  • 1
  • 3
  • 14
  • 1
    Note: this is the maximum heap size at that moment. The actual heap used is likely to be less and even the maximum available heap can vary based on the size of the survivor spaces (as you can only use one of the two survivor spaces at any one time) The actual memory usage is greater as there is non-heap memory for the program/code, perm gen/metaspace threads, direct memory etc. – Peter Lawrey Jan 10 '16 at 18:15
  • Precisely. To expand for those who happen to stumble accross this: This solution will tell how much heap the JVM can allocate, but not how much physical and/or virtual memory is allocated by Windows to the process. E.g. I have `maxMemory()` of 4GB, yet due to C++ code used via javacpp the process peaks at around 11GB in Windows. – Koenigsberg Oct 12 '18 at 07:20