Basic Usage - Using DirectByteBuffer

suggest change

DirectByteBuffer is special implementation of ByteBuffer that has no byte[] laying 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 main characteristics of DirectByteBuffer is that JVM will try to natively work on allocated memory without any additional buffering so operations performed on it may be faster then those performed on ByteBuffers with arrays lying underneath.

It is recomended to use DirectByteBuffer with heavy IO operations that rely on speed of execution, like real time communication.

We have to be aware that if we try using array() method we will get UnsupportedOperationException. So it is a good practice to chech whether our ByteBuffer has it (byte array) before we try to access it:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


ByteBuffer:
* Basic Usage - Using DirectByteBuffer

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
46 ByteBuffer
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap