Java allows application to access non heap memory by using direct byte buffer. Many high performance application uses direct byte buffer, along with
memory mapped file for high speed IO. And, while the
ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of Garbage collection scope. Which means garbage collector can not reclaim this memory. It is often used to store large data e.g. order or static data cache. Since generally your program allocates large buffer e.g. size of
1GB or
2GB, you get "
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running following code
ByteBuffer buffer = ByteBuffer.allocateDirect(SIZE_OF_BUFFER)
java.lang.OutOfMemoryError: Direct buffer memory
at java.nio.Bits.reserveMemory(Bits.java:632)
at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:97)
at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:288)
Now there could be multiple reasons for that e.g. either your system doesn't have enough
heap memory, mostly the case when you are requesting a large chunk of memory, or memory hasn't been free from last usage. First case, is pretty straight forward, as your application will fail to start in first attempt itself, and will not work until you add extra memory or reduce size of direct byte buffer. In second case, there could be either memory leak, where your code is holding reference of
ByteBuffer to prevent them from being garbage collected, and subsequently your off heap buffer.