Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate memory usage of a Java program?

If I use the Runtime class (freeMemory(), totalMemory(), and gc()), then it gives me memory above MB (i.e. 1,000,000 bytes).

But if I run the same code on any online compiler, then they show memory used in KB (i.e. 1000 bytes). This is a huge difference.

This means Runtime does not show the actual memory used by the program.

I need to calculate actual memory used by the program. What is the way these online compilers use to calculate memory used by the program?

like image 984
Ganesh S Avatar asked Jun 20 '16 06:06

Ganesh S


People also ask

What is memory usage in Java?

A MemoryUsage object represents a snapshot of memory usage. Instances of the MemoryUsage class are usually constructed by methods that are used to obtain memory usage information about individual memory pool of the Java virtual machine or the heap or non-heap memory of the Java virtual machine as a whole.

How much memory does my Java application need?

When you run the JVM without the maximum heap size for the server JVM it uses 1/4 of main memory up to 32 GB. If you use the 32-bit windows client VM, it uses 64MB or 128MB. The best way to determine the required memory consumption is to test you application with different memory sizes.


2 Answers

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.
like image 168
Amit Bhati Avatar answered Sep 17 '22 13:09

Amit Bhati


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.

like image 40
Rohit Gupta Avatar answered Sep 19 '22 13:09

Rohit Gupta