Java – programmatically check the available heapsize?
•
Java
I'm using eclipse The problem is that if less than 512MB of memory is allocated, my application crashes Is there any way to check the program's available memory before starting a large memory exhaustion process?
long heapSize = Runtime.getRuntime().totalMemory(); System.out.println("Heap Size = " + heapSize);
The problem is that this gives the JVM heap size Even if you add it, you can't use eclipse In eclipse, if I change VM parameters, it works However, the printout of the above statement is always the same Is there a command that I can know exactly how much memory I have allocated for a particular application?
Solution
You can use JMX to collect heap memory usage at run time
Code example:
import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.lang.management.MemoryUsage; for (MemoryPoolMXBean mpBean: ManagementFactory.getMemoryPoolMXBeans()) { if (mpBean.getType() == MemoryType.HEAP) { System.out.printf( "Name: %s: %s\n",mpBean.getName(),mpBean.getUsage() ); } }
Output example:
Name: Eden Space: init = 6619136(6464K) used = 3754304(3666K) committed = 6619136(6464K) max = 186253312(181888K) Name: Survivor Space: init = 786432(768K) used = 0(0K) committed = 786432(768K) max = 23265280(22720K) Name: Tenured Gen: init = 16449536(16064K) used = 0(0K) committed = 16449536(16064K) max = 465567744(454656K)
If you have questions about "Eden space" or "survivor space", please check how is the JAVA memory pool divided
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码