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

If I create a buffer through ByteBuffer.allocateDirect() , the memory exists outside the Java heap. Is there a way to measure the use of this type of memory from my application in a cross-platform way, similar to how I can measure the use of the Java heap with Runtime.totalMemory() and Runtime.freeMemory() ?

+6
source share
2 answers

You can use reflexes to get Bits.reservedMemory in OpenJDK / HotSpot Java 7. There is no platform-independent way, and this will show you using ByteBuffer.allocateDirect (), and not another way of allocating your own memory.

An alternative is parsing /proc/{pid}/maps and excluding file associations. This is the approximation of virtual memory that your process is using.

+3
source

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

 List<BufferPoolMXBean> 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 is the toMB function:

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

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

+1
source

Source: https://habr.com/ru/post/958343/


All Articles