Check available heapSize programmatically?

后端 未结 1 642
情话喂你
情话喂你 2021-01-02 08:46

I am using Eclipse. The problem is my application crashes if the allocated memory is less then 512MB. Now is there anyway to check the available memory for a program before

相关标签:
1条回答
  • 2021-01-02 09:36

    You could use JMX to collect the usage of heap memory at runtime.


    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 your have question about "Eden Space" or "Survivor Space", check out How is the java memory pool divided

    0 讨论(0)
提交回复
热议问题