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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With