Java YoungGen和OldGen如何得到?

How to get from Java YoungGen and OldGen?

如何从 Java 获取以下 YoungGen (Eden, Survivor0,Survivor1), OldGen 区域的已分配和空闲内存的值?

我看到 tomcat 页面显示此信息,我如何从 java 代码中获取它?

关于maxMemory()totalMemory()freeMemory(),我知道,但是还不完全清楚如何准确获取内存区域的值,如Tomcat ,例如。

您可以使用 the Management API, most notably the MemoryMXBean.

例如

import java.lang.management.*;

class Memory {
    public static void main(String[] args) {
        MemoryMXBean m = ManagementFactory.getMemoryMXBean();
        for(MemoryType type: MemoryType.values()) {
            usage(type, type == MemoryType.HEAP?
                m.getHeapMemoryUsage(): m.getNonHeapMemoryUsage());
            System.out.println();
            for(MemoryPoolMXBean mp: ManagementFactory.getMemoryPoolMXBeans())
                if(mp.getType() == type) usage(mp.getName(), mp.getUsage());
            System.out.println();
        }
    }
  
    private static void usage(Object header, MemoryUsage mu) {
        long used = mu.getUsed(), max = mu.getMax();
        System.out.printf(
            max > 0? "%-30s %,d (%,d MiB) of %,d (%,d MiB)%n": "%-30s %,d (%,d MiB)%n",
            header, used, used >>> 20, max, max >>> 20);
    }
}

Demo on Ideone

Heap memory                    2,820,696 (2 MiB) of 1,037,959,168 (989 MiB)

Tenured Gen                    0 (0 MiB) of 715,849,728 (682 MiB)
Eden Space                     4,231,056 (4 MiB) of 286,326,784 (273 MiB)
Survivor Space                 0 (0 MiB) of 35,782,656 (34 MiB)

Non-heap memory                2,833,312 (2 MiB) of 352,321,536 (336 MiB)

CodeHeap 'non-nmethods'        1,079,040 (1 MiB) of 5,828,608 (5 MiB)
Metaspace                      1,078,264 (1 MiB) of 67,108,864 (64 MiB)
CodeHeap 'profiled nmethods'   489,472 (0 MiB) of 122,912,768 (117 MiB)
Compressed Class Space         114,560 (0 MiB) of 33,554,432 (32 MiB)
CodeHeap 'non-profiled nmethods' 89,856 (0 MiB) of 122,916,864 (117 MiB)

有关如何获取有关垃圾回收及其结果的通知的示例,请参阅