How to calculate memory usage of a Java program?

First calculate the memory used before your code execution i.e. first line of your code.

long beforeUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

Calculate the memory used after your code execution:-

long afterUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

Then you can do:

long actualMemUsed=afterUsedMem-beforeUsedMem;

It will give you actual memory utilized by your program.

For further memory analysis your best bet is any profiler tool like jvisualvm.

  • Do remember it, that Runtime.getRuntime().totalMemory(), this memory is total memory available to your JVM.
  • java -Xms512m -Xmx1024m , it means that total memory of your program will start with 512MB, which may lazily loaded to max of 1024MB.
  • So if you are running same program, on different JVMs, Runtime.getRuntime().totalMemory() might give you different results.

You can use top command in ubuntu to check % CPU use or % memory use while running the java programme.

top command will give you these many information.

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND

just type top and hit enter in your terminal & check java in command section.