开发者

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

开发者 https://www.devze.com 2022-12-31 20:00 出处:网络
I want to calculate the heap usage for my app. I would like to get a procent value of Heap size only.

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.

开发者_StackOverflow社区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()


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.


This information is exposed over the JMX management interface. If you simply want to look at it, JConsole or visualvm (part of the JDK, installed in JAVA_HOME/bin) can display nice graphs of a JVM's memory usage, optionally broken down into the various memory pools.

This interface can also be accessed programmatically; see MemoryMXBean.


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


There really is no good answer, since how much heap memory the JVM has free is not the same as how much heap memory the operating system has free, which are both not the same as how much heap memory can be assigned to your application.

This is because the JVM and OS heaps are different. When the JVM runs out of memory, it may run garbage-collection, defragment its own heap, or request more memory from the OS. Since unused non-garbage-collected objects still exist, but are technically "free", they make the concept of free memory a bit fuzzy.

Also, heap memory fragments; how/when/if memory is defragmented is up to the implementation of the JVM/OS. For example, the OS-heap may have 100MB of free memory, but due to fragmentation, the largest available contiguous space may be 2MB. Thus, if the JVM requests 3MB, it may get an out-of-memory error, even though 100MB are still available. It is not possible for the JVM to know ahead of time that the OS won't be able to allocate that 3MB.

0

精彩评论

暂无评论...
验证码 换一张
取 消