Is there a way to measure direct memory usage in Java?

前端 未结 2 1460
我在风中等你
我在风中等你 2020-12-28 20:56

If I create a buffer via ByteBuffer.allocateDirect(), the memory exists outside of the Java heap. Is there a way to measure this kind of memory usage from my a

2条回答
  •  有刺的猬
    2020-12-28 21:30

    You can use MXBeans to get the memory used by the direct byte buffers and mapped byte buffers:

    List pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) {
        System.out.println(pool.getName());
        System.out.println(pool.getCount());
        System.out.println("memory used " + toMB(pool.getMemoryUsed()));
        System.out.println("total capacity" + toMB(pool.getTotalCapacity()));
        System.out.println();
    }
    

    prints something like:

    direct
    122
    memory used 456.1562509536743 MB
    total capacity456.15625 MB
    
    mapped
    0
    memory used 0.0 MB
    total capacity0.0 MB
    

    where toMB function is this:

    private static String toMB(long init) {
        return (Long.valueOf(init).doubleValue() / (1024 * 1024)) + " MB";
    }
    

    However, I am not 100% sure if direct byte buffers are the only things that can live in the direct memory. Perhaps there are other things...

提交回复
热议问题