Basic Usage - Using DirectByteBuffer
suggest changeA direct ByteBuffer (implemented by DirectByteBuffer) has no byte[] underneath.
We can allocate such ByteBuffer by calling:
ByteBuffer directBuffer = ByteBuffer.allocateDirect(16);
This operation will allocate 16 bytes of memory. The contents of direct buffers may reside outside of the normal garbage-collected heap.
We can verify whether ByteBuffer is direct by calling:
directBuffer.isDirect(); // true
The JVM can operate on that memory without copying it into a heap byte[], so I/O on a direct buffer can be faster than I/O on a heap buffer.
Direct buffers are a good fit for heavy I/O that is sensitive to copying, such as real-time communication. They are not automatically faster for small buffers, and they are more expensive to allocate.
Calling array() on a direct buffer throws UnsupportedOperationException. Check hasArray() before calling array():
byte[] arrayOfBytes;
if(buffer.hasArray()) {
arrayOfBytes = buffer.array();
}
Another use of direct byte buffer is interop through JNI. Since a direct byte buffer does not use a byte[], but an actual block of memory, it is possible to access that memory directly through a pointer in native code. This can save a bit of trouble and overhead on marshalling between the Java and native representation of data.
The JNI interface defines several functions to handle direct byte buffers: NIO Support.