0

I use ByteBuffer.allocateDirect(int) to allocate direct buffer(100M) on non-heap space until java.lang.OutOfMemoryError: Direct buffer memory error thrown.

But when I use jconsole to monitoring the non-heap memory usage, no direct buffer used memory is shown.

import java.nio.ByteBuffer;
import java.util.LinkedList;

public class BufferTest {
    public static void main(String[] args) throws InterruptedException {
        LinkedList<ByteBuffer> ll = new LinkedList<ByteBuffer>();
        int i = 0;

        while (true) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(100 * 1024 * 1024);
            while (buffer.hasRemaining()) {
                buffer.put((byte) 1);
            }
            ll.add(buffer);

            System.out.println(i++ + "\t" + buffer.isDirect() + "\t" + buffer.limit());
            Thread.sleep(1000);
        }
    }
}

enter image description here

Machi
  • 403
  • 2
  • 14
  • 1
    How long did the program run/how many messages did it print? – Holger Jul 01 '22 at 07:52
  • @Holger Each second the program allocates a direct buffer of size 100M. After 34 seconds, which means 3.4G non-heap memory is used, "OutOfMemoryError: Direct buffer memory" error thrown. – Machi Jul 01 '22 at 08:34
  • 3
    Can confirm. This memory does not appear in the “non-heap memory”. Look at the “MBeans” tab under “java.nio” → “BufferPool” → “direct” → “MemoryUsed”; this property does reflect the allocations. This seems to be the way, JMX reports the values, regardless of which tool you use for the visualization. – Holger Jul 01 '22 at 09:48
  • @Holger Thanks very much. I can see the data now. – Machi Jul 01 '22 at 09:57

0 Answers0