您可以使用the Management API,尤其是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)
请参阅this answer,了解如何获取有关垃圾回收及其结果的通知的示例。