Skip to content

ByteBuffer types and allocation

In Java NIO, the ByteBuffer class serves as the primary container for data manipulation, supporting operations to mark, reset, and flip buffers to manage read/write states^[600-developer__java__java-io__bio-nio-aio.md]. To accommodate different performance and memory requirements, buffers can be allocated in two distinct types based on the memory region they utilize.

Allocation Types

Buffers are typically categorized based on where they are stored in memory: the Java Heap or native system memory.

HeapByteBuffer

A HeapByteBuffer is created using the standard memory allocation mechanism.^[600-developer__java__java-io__bio-nio-aio.md] It is allocated within the standard JVM heap space using the allocate method.^[600-developer__java__java-io__bio-nio-aio.md] Because these buffers reside on the heap, they are subject to standard Java Garbage Collection management and are easier to work with directly from Java code.

DirectByteBuffer

A DirectByteBuffer is allocated outside of the standard JVM heap, in native system memory.^[600-developer__java__java-io__bio-nio-aio.md] This type is created using the allocateDirect method.^[600-developer__java__java-io__bio-nio-aio.md] The primary advantage of using a direct buffer is its ability to perform zero copy I/O operations, which avoids copying data between the Java heap and native memory layers, thereby improving efficiency in certain I/O scenarios.^[600-developer__java__java-io__bio-nio-aio.md]

Operations

Beyond allocation, ByteBuffer provides several methods for manipulating data states:

  • asReadOnlyBuffer: Creates a new, read-only buffer that shares content with the original buffer.^[600-developer__java__java-io__bio-nio-aio.md]
  • compact: Used to prepare a buffer for relative write operations while retaining unread data.^[600-developer__java__java-io__bio-nio-aio.md]
  • [[Buffer properties]]
  • [[Zero copy]]
  • [[Java NIO]]

Sources

^[600-developer__java__java-io__bio-nio-aio.md]