Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get just free heap size (not together w stack/method mem) in Java?

I want to calculate the heap usage for my app. I would like to get a procent value of Heap size only.

How do I get the value in code for the current running app?

EDIT

There was an upvoted answer that was NOT complete/correct. The values returned by those methods include stack and method area too, and I need to monitor only heap size.
With that code I got HeapError exception when I reached 43%, so I can't use those methods to monitor just heap

Runtime.getRuntime().totalMemory()
like image 792
Pentium10 Avatar asked May 21 '10 18:05

Pentium10


People also ask

Can you list the differences between heap and stack memory?

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.

Why do we have difference memories like heap memory stack memory dynamic memory?

Stack space is mainly used for storing order of method execution and local variables. Stack always stored blocks in LIFO order whereas heap memory used dynamic allocation for allocating and deallocating memory blocks. Memory allocated to the heap lives until one of the following events occurs : Program terminated.

How does Java allocate stack and heap memory?

Stack and Heap memory are allocated to a program by the Java Virtual Machine (JVM). All the primitive data types and references to objects created inside a method are stored in the stack. Stack memory is accessed in a Last-In-First-Out (LIFO) manner. The size of the stack is small and fixed.

How do I free up heap memory?

Once an object is not referenced by any other object, it can be cleared out of the heap, in order for the JVM to reclaim and reuse that space. The execution thread that is responsible to clear the heap space is the Garbage Collector.


1 Answers

dbyme's answer is not accurate - these Runtime calls give you an amount of memory used by JVM, but this memory does not consist only of heap , there is also stack and method area e.g.

like image 181
Rostislav Matl Avatar answered Sep 28 '22 23:09

Rostislav Matl