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

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

How to get the value in the code for the currently running application?

EDIT

An answer that was NOT complete / correct was confirmed. The values โ€‹โ€‹returned by these methods also include the stack and method area, and I need to track only the heap size.
With this code, I got a HeapError exception when I reached 43%, so I cannot use these methods to control only the heap

Runtime.getRuntime().totalMemory() 
+7
java heap
source share
4 answers

Dbyme's answer is not exact - these Runtime calls give you the amount of memory used by the JVM, but this memory is not just a heap , there is also a stack area and a method, for example

+2
source share

This information is displayed through the JMX management interface. If you just want to look at it, JConsole or visualvm (part of the JDK installed in JAVA_HOME / bin) can display nice JVM memory usage graphs, optionally divided into different memory pools.

This interface can also be accessed programmatically; see MemoryMXBean .

+1
source share

MemoryMXBean bean = ManagementFactory.getMemoryMXBean (); bean.getHeapMemoryUsage () getUsed () ;.

+1
source share

Actually, there is no good answer, since the amount of heap memory that the JVM has does not coincide with how free the operating system is in the heap, and it is not the same as the amount of heap memory that can be assigned to your application.

This is because the JVM and OS heaps are different. When the JVM runs out of memory, it can start garbage collection, defragment its heap, or request more memory from the OS. Since unused garbage-free objects still exist, but are technically โ€œfreeโ€, they make the concept of free memory a bit fuzzy.

In addition, heap memory fragments; how / when / if memory defragmentation depends on the implementation of the JVM / OS. For example, an OS heap may have 100 MB of free memory, but due to fragmentation, the largest available contiguous space may be 2 MB. Thus, if the JVM requests 3 MB, it may receive an error due to memory, although 100 MB is still available. The JVM cannot know in advance that the OS will not be able to allocate this 3 MB.

0
source share

All Articles