Search code examples
javamemorymemory-managementgarbage-collectionheap-memory

How to get from Java YoungGen and OldGen?


How can I get the value of the allocated and free memory of the following YoungGen (Eden, Survivor0,Survivor1), OldGen areas from Java?

I see that the tomcat page displays this information, how can I get it from the java code?

About maxMemory(), totalMemory(), freeMemory(), I know, But it is not entirely clear how to get the value of exactly memory areas, as Tomcat does, for example.


Solution

  • You can use the Management API, most notably the MemoryMXBean.

    For example

    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)
    

    See this answer for an example of how to get notifications about garbage collections and their results.