ByteBuffer
A ByteBuffer is a fixed-size block of bytes with a cursor, used by NIO channels, binary protocols and file formats. Almost every ByteBuffer bug comes from its three indexes, position, limit and capacity, being in the wrong state. This page explains the buffer model, prints the indexes after every operation, runs the common traps, reads and writes typed data in both byte orders, decodes frames that arrive in pieces, and compares heap and direct buffers.
Contents
How a buffer keeps track of its data
java.nio.ByteBuffer
- capacity: the size, fixed at creation.
- position: where the next relative
orget happens; it moves forward with each one.put - limit: the first index that must not be read or written. While writing it is usually the capacity; while reading it marks the end of the valid data.
- mark: an optional saved position, restored by
.reset()
The same buffer is used for writing and then reading, and a few methods switch between the two modes by moving the indexes; none of them changes the bytes themselves. The flip()clear()compact()rewind()
| Created by | Since | Memory | Best for |
|---|---|---|---|
ByteBuffer.allocate(n) | Java 1.4 | A byte[] | Parsing and building binary data in memory |
ByteBuffer.wrap(array) | Java 1.4 | Your existing array, shared | Viewing bytes you already have |
ByteBuffer.allocateDirect(n) | Java 1.4 | Native memory outside the heap | Long-lived buffers for channel and socket I/O |
FileChannel.map(...) | Java 1.4 | A memory-mapped region of a file | Random access to large files |
slice()duplicate()asIntBuffer()asReadOnlyBuffer() | Java 1.4; slice(index, length) | A view of another buffer's bytes | Windows and typed views without copying |
For off-heap memory with explicit lifetimes and no 2 GB limit, Java 22 added the Foreign Function and Memory API; see
Watching position, limit and capacity
An 8-byte buffer receives three bytes, is flipped, read partly, compacted and cleared, and the program prints the indexes after each step.
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
public class BufferState {
static void show(String step, ByteBuffer b) {
System.out.printf("%-22s position=%d limit=%d capacity=%d remaining=%d%n",
step, b.position(), b.limit(), b.capacity(), b.remaining());
}
public static void main(String[] args) {
ByteBuffer buf = ByteBuffer.allocate(8);
show("allocate(8)", buf);
buf.put((byte) 'H').put((byte) 'i').put((byte) '!');
show("after 3 puts", buf);
buf.flip(); // switch from writing to reading
show("flip()", buf);
System.out.println("read: " + (char) buf.get() + (char) buf.get());
show("after 2 gets", buf);
buf.compact(); // keep unread bytes, get ready to write more
show("compact()", buf);
buf.clear(); // forget everything: ready to write from 0
show("clear()", buf);
try {
ByteBuffer.allocate(2).put((byte) 1).put((byte) 2).put((byte) 3);
} catch (BufferOverflowException e) {
System.out.println("putting 3 bytes into a 2-byte buffer: BufferOverflowException");
}
}
}
Output:
allocate(8) position=0 limit=8 capacity=8 remaining=8
after 3 puts position=3 limit=8 capacity=8 remaining=5
flip() position=0 limit=3 capacity=8 remaining=3
read: Hi
after 2 gets position=2 limit=3 capacity=8 remaining=1
compact() position=1 limit=8 capacity=8 remaining=7
clear() position=0 limit=8 capacity=8 remaining=8
putting 3 bytes into a 2-byte buffer: BufferOverflowException
- After three puts, position is 3 and 5 bytes remain for writing.
moved limit to 3 and position to 0: exactly the three written bytes are now readable.flip() - Two gets read "Hi" and left position 2, with 1 byte remaining.
moved that unread "!" to index 0, set position to 1 and limit to 8, so new bytes are appended after it. This is the step that makes partial reads from a network work.compact() reset the indexes without erasing anything: the bytes are still in the buffer but will be overwritten. Writing past the limit throwsclear() .BufferOverflowException
Five ByteBuffer traps
The traps below all compile, and most do not throw. Each one shows the wrong result next to the right one.
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.charset.StandardCharsets;
public class BufferTraps {
public static void main(String[] args) {
// 1. Forgetting flip(): reading starts at the write position
ByteBuffer buf = ByteBuffer.allocate(16);
buf.put("hello".getBytes(StandardCharsets.US_ASCII));
System.out.println("1. without flip, remaining to read: " + buf.remaining()
+ " (the 11 unused bytes, all zero)");
buf.flip();
System.out.println("1. after flip, decoded: "
+ StandardCharsets.US_ASCII.decode(buf));
// 2. Reading past the limit
ByteBuffer two = ByteBuffer.wrap(new byte[] {1, 2});
try {
two.getInt(); // needs 4 bytes
} catch (BufferUnderflowException e) {
System.out.println("2. getInt() with 2 bytes left: BufferUnderflowException");
}
// 3. array() returns the WHOLE backing array, not just the data
ByteBuffer data = ByteBuffer.allocate(8).put((byte) 9).put((byte) 8);
System.out.println("3. array().length = " + data.array().length
+ " although only " + data.position() + " bytes were written");
ByteBuffer slice = ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}).position(2).slice();
System.out.println("3. slice: get(0) = " + slice.get(0) + ", but array()[0] = "
+ slice.array()[0] + "; arrayOffset = " + slice.arrayOffset());
// 4. duplicate() shares the bytes but has its own position and limit
ByteBuffer original = ByteBuffer.wrap("abc".getBytes(StandardCharsets.US_ASCII));
ByteBuffer copy = original.duplicate();
copy.get();
copy.put(1, (byte) 'X');
System.out.println("4. original position " + original.position() + ", copy position "
+ copy.position() + ", original sees " + (char) original.get(1));
// 5. A read-only view rejects writes but still sees changes made through the original
ByteBuffer ro = original.asReadOnlyBuffer();
try {
ro.put(0, (byte) 'z');
} catch (ReadOnlyBufferException e) {
System.out.println("5. put on read-only view: ReadOnlyBufferException");
}
original.put(0, (byte) 'Q');
System.out.println("5. read-only view sees the original's change: " + (char) ro.get(0));
}
}
Output:
1. without flip, remaining to read: 11 (the 11 unused bytes, all zero)
1. after flip, decoded: hello
2. getInt() with 2 bytes left: BufferUnderflowException
3. array().length = 8 although only 2 bytes were written
3. slice: get(0) = 2, but array()[0] = 0; arrayOffset = 2
4. original position 0, copy position 1, original sees X
5. put on read-only view: ReadOnlyBufferException
5. read-only view sees the original's change: Q
- Without
, a reader starts at position 5 and sees the 11 unused zero bytes as data. Writing such a buffer to a channel sends 11 zero bytes instead of "hello". Afterflip() the content decoded correctly.flip() - A relative
needs 4 remaining bytes; with 2 it throwsgetInt() . CheckBufferUnderflowException before reading a value, as the frame decoder below does.remaining() returns the entire backing array, 8 bytes, although only 2 were written; usearray() orposition() for the real length. A slice starting at index 2 has its own index 0 atlimit() 2 of the shared array, so code that usesarrayOffset() on a slice must add the offset.array() shares the bytes but has independent indexes. Reading from the copy moved only its position, while a write through the copy was visible in the original.duplicate()- A read-only view rejects writes with
, but it is a view, not a snapshot: a change made through the original buffer showed up in it.ReadOnlyBufferException
Typed values and byte order
A byte buffer can read and write shortintlongfloatdoublechar0x01020304
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HexFormat;
public class TypesAndOrder {
public static void main(String[] args) {
HexFormat hex = HexFormat.ofDelimiter(" ");
ByteBuffer big = ByteBuffer.allocate(4); // big-endian by default
big.putInt(0x01020304);
System.out.println("BIG_ENDIAN 0x01020304 -> " + hex.formatHex(big.array()));
ByteBuffer little = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
little.putInt(0x01020304);
System.out.println("LITTLE_ENDIAN 0x01020304 -> " + hex.formatHex(little.array()));
System.out.println("this machine: " + ByteOrder.nativeOrder());
// A small binary record: type (1 byte), id (int), price (double)
ByteBuffer record = ByteBuffer.allocate(13);
record.put((byte) 7).putInt(1234).putDouble(19.99);
record.flip();
System.out.println("record bytes: " + hex.formatHex(record.array()));
System.out.println("decoded: type=" + record.get() + " id=" + record.getInt()
+ " price=" + record.getDouble());
// Absolute get/put use an index and leave position alone
int id = record.getInt(1);
System.out.println("absolute getInt(1) = " + id + ", position stays " + record.position());
// Direct vs heap buffers
ByteBuffer heap = ByteBuffer.allocate(16);
ByteBuffer direct = ByteBuffer.allocateDirect(16);
System.out.println("heap: isDirect=" + heap.isDirect() + " hasArray=" + heap.hasArray());
System.out.println("direct: isDirect=" + direct.isDirect()
+ " hasArray=" + direct.hasArray());
}
}
Output:
BIG_ENDIAN 0x01020304 -> 01 02 03 04
LITTLE_ENDIAN 0x01020304 -> 04 03 02 01
this machine: LITTLE_ENDIAN
record bytes: 07 00 00 04 d2 40 33 fd 70 a3 d7 0a 3d
decoded: type=7 id=1234 price=19.99
absolute getInt(1) = 1234, position stays 13
heap: isDirect=false hasArray=true
direct: isDirect=true hasArray=false
- A new buffer is always
, most significant byte first, which is the network byte order and the order of Java'sBIG_ENDIAN .DataOutputStream stores the same int as 04 03 02 01, the order used by x86 and ARM processors and by formats such as ZIP and BMP. This machine's native order is little-endian.LITTLE_ENDIAN - The record took 1 + 4 + 8 = 13 bytes: 07, then 1234 as 00 00 04 d2, then the IEEE 754 bits of 19.99. Reading must use the same order and the same sequence of types as writing, because the bytes carry no type information.
- Absolute methods such as
take an index and leave position unchanged, which is convenient for peeking at a header.getInt(1) - A heap buffer has an accessible array; a direct buffer does not, so
is false andhasArray() would throwarray() .UnsupportedOperationException
Decoding frames that arrive in pieces
Network data arrives in chunks that have nothing to do with message boundaries. A common protocol prefixes each message with its length. Three messages are encoded that way, 23 bytes in all, and delivered in chunks of 4, 9, 3 and 7 bytes, so that frames are split at awkward places, even inside a length field.
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class FrameDecoder {
// Wire format: 2-byte big-endian length, then that many bytes of UTF-8 text
static byte[] encode(String... messages) {
int size = 0;
for (String m : messages) {
size += 2 + m.getBytes(StandardCharsets.UTF_8).length;
}
ByteBuffer out = ByteBuffer.allocate(size);
for (String m : messages) {
byte[] b = m.getBytes(StandardCharsets.UTF_8);
out.putShort((short) b.length).put(b);
}
return out.array();
}
// Accumulates incoming bytes and returns every complete frame
static List<String> decode(ByteBuffer in) {
List<String> frames = new ArrayList<>();
in.flip(); // switch to reading
while (in.remaining() >= 2) {
int length = in.getShort(in.position()) & 0xFFFF; // peek, do not consume
if (in.remaining() < 2 + length) {
break; // frame incomplete: wait for more
}
in.getShort();
byte[] body = new byte[length];
in.get(body);
frames.add(new String(body, StandardCharsets.UTF_8));
}
in.compact(); // keep the partial frame, write after it
return frames;
}
public static void main(String[] args) {
byte[] wire = encode("hello", "binary", "frames");
System.out.println("wire size: " + wire.length + " bytes");
// The network delivers the bytes in uneven chunks, splitting frames
int[] chunkSizes = {4, 9, 3, 7};
ByteBuffer buffer = ByteBuffer.allocate(64);
int offset = 0;
for (int size : chunkSizes) {
buffer.put(wire, offset, size);
offset += size;
List<String> frames = decode(buffer);
System.out.printf("chunk of %d bytes -> frames %s, %d bytes waiting%n",
size, frames, buffer.position());
}
}
}
Output:
wire size: 23 bytes
chunk of 4 bytes -> frames [], 4 bytes waiting
chunk of 9 bytes -> frames [hello], 6 bytes waiting
chunk of 3 bytes -> frames [binary], 1 bytes waiting
chunk of 7 bytes -> frames [frames], 0 bytes waiting
- The first chunk held the 2-byte length of "hello" (5) and only 2 of its 5 bytes, so no frame was complete and all 4 bytes stayed in the buffer.
- After the second chunk, "hello" was complete and returned; the remaining 6 bytes were the length of "binary" plus its first 4 bytes. Each chunk is appended with
, thenput flips, reads every complete frame, and callsdecode to keep the incomplete rest for the next round.compact() - The length is peeked with the absolute
before deciding whether to consume anything. ThegetShort(position) treats it as unsigned, since Java's& 0xFFFF is signed and a length above 32,767 would otherwise read as negative.short
Views, slices and wrapped arrays
Views look at the same memory in another way without copying. The program views four little-endian ints as an IntBufferslice(index, length)
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Arrays;
public class ViewsAndSlices {
public static void main(String[] args) {
// Four ints written as bytes, then viewed as an IntBuffer without copying
ByteBuffer bytes = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);
bytes.putInt(10).putInt(20).putInt(30).putInt(40).flip();
IntBuffer ints = bytes.asIntBuffer();
System.out.println("asIntBuffer: " + ints.remaining() + " ints, ints.get(2) = "
+ ints.get(2) + ", order " + ints.order());
ints.put(0, 99); // writes through to the bytes
System.out.println("byte 0 after ints.put(0, 99): " + bytes.get(0));
// slice(index, length) (Java 13): a window over part of the buffer
ByteBuffer window = bytes.slice(4, 8);
System.out.println("slice(4, 8): capacity " + window.capacity() + ", first int "
+ window.order(ByteOrder.LITTLE_ENDIAN).getInt(0));
// Absolute bulk get (Java 13): copy a range without moving position
byte[] range = new byte[4];
bytes.get(8, range);
System.out.println("bulk get(8, 4 bytes): " + Arrays.toString(range)
+ ", position still " + bytes.position());
// wrap shares the caller's array: changes go both ways
byte[] array = {1, 2, 3};
ByteBuffer wrapped = ByteBuffer.wrap(array);
wrapped.put(0, (byte) 7);
array[2] = 9;
System.out.println("wrapped array after changes: " + Arrays.toString(array)
+ ", buffer get(2) = " + wrapped.get(2));
}
}
Output:
asIntBuffer: 4 ints, ints.get(2) = 30, order LITTLE_ENDIAN
byte 0 after ints.put(0, 99): 99
slice(4, 8): capacity 8, first int 20
bulk get(8, 4 bytes): [30, 0, 0, 0], position still 0
wrapped array after changes: [7, 2, 9], buffer get(2) = 9
gave a view of 4 ints in the byte buffer's order, little-endian here. Writing 99 through the view changed byte 0 of the byte buffer, because both share memory.asIntBuffer- The slice from index 4 with length 8 starts at the second int, 20. Note that the slice was created big-endian: a new view does not inherit the byte order, which is why the code sets it again. This is a frequent source of garbled numbers.
- The absolute bulk
copied the bytes of 30 (30, 0, 0, 0 in little-endian) and left position at 0.get(8, array) uses the caller's array directly: a write through the buffer and a write to the array were each visible through the other.wrap
Reading a file through a channel, and heap versus direct
Channels read into and write from byte buffers. A deliberately small 16-byte buffer reads a 43-character sentence, so the flip and clear cycle runs several times.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class ChannelRead {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("buffer", ".txt");
Files.writeString(file, "The quick brown fox jumps over the lazy dog");
ByteBuffer buf = ByteBuffer.allocate(16); // deliberately small
StringBuilder text = new StringBuilder();
int reads = 0;
try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) {
while (ch.read(buf) != -1) { // fill the buffer
reads++;
buf.flip(); // prepare to read it
text.append(StandardCharsets.UTF_8.decode(buf));
buf.clear(); // prepare to fill again
}
}
System.out.println(reads + " reads of up to 16 bytes: " + text);
Files.delete(file);
}
}
Output:
3 reads of up to 16 bytes: The quick brown fox jumps over the lazy dog
Three reads of up to 16 bytes covered the 43 bytes: fill, flip()clear()readCharsetDecodercompact()
A heap buffer passed to a channel is copied into a temporary direct buffer by the JDK for the actual system call, because the garbage collector may move heap arrays. A direct buffer avoids that copy, but costs more to allocate and is freed only when the buffer object is garbage-collected, through a
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class BufferSpeed {
interface Job {
long run() throws IOException;
}
static long best(Job job) throws IOException {
long best = Long.MAX_VALUE;
for (int r = 0; r < 3; r++) {
long t0 = System.nanoTime();
job.run();
best = Math.min(best, System.nanoTime() - t0);
}
return best / 1000000;
}
// Reads the whole file through one reusable buffer and returns the byte count
static long readAll(Path file, ByteBuffer buf) throws IOException {
long total = 0;
try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) {
int n;
while ((n = ch.read(buf)) != -1) {
total += n;
buf.clear();
}
}
return total;
}
public static void main(String[] args) throws IOException {
// 1. Allocation: 20,000 buffers of 64 KB
long heapAlloc = best(() -> {
long n = 0;
for (int i = 0; i < 20000; i++) {
n += ByteBuffer.allocate(65536).capacity();
}
return n;
});
long directAlloc = best(() -> {
long n = 0;
for (int i = 0; i < 20000; i++) {
n += ByteBuffer.allocateDirect(65536).capacity();
}
return n;
});
System.out.printf("allocate 20,000 x 64 KB buffers: heap %,4d ms, direct %,4d ms%n",
heapAlloc, directAlloc);
// 2. Channel I/O: read a 256 MB file through one reused 64 KB buffer
Path file = Files.createTempFile("big", ".bin");
byte[] chunk = new byte[1 << 20];
try (FileChannel out = FileChannel.open(file, StandardOpenOption.WRITE)) {
for (int i = 0; i < 256; i++) {
out.write(ByteBuffer.wrap(chunk));
}
}
ByteBuffer heap = ByteBuffer.allocate(65536);
ByteBuffer direct = ByteBuffer.allocateDirect(65536);
long bytes = readAll(file, heap);
long h = best(() -> readAll(file, heap));
long d = best(() -> readAll(file, direct));
System.out.printf("read %d MB through a 64 KB buffer: heap %,4d ms, direct %,4d ms%n",
bytes >> 20, h, d);
Files.delete(file);
}
}
Output (2-CPU Linux machine, JDK 21, best of 3):
allocate 20,000 x 64 KB buffers: heap 216 ms, direct 201 ms
read 256 MB through a 64 KB buffer: heap 40 ms, direct 32 ms
- Allocation times were close, with direct buffers a little slower in most repeated runs: native memory must be reserved, zeroed and registered for cleanup, while zeroing 64 KB dominates both. Allocate direct buffers once and reuse them; never allocate one per request.
- Reading a 256 MB file through a reused 64 KB buffer was slightly faster with the direct buffer, because no extra copy was needed. With the file in the page cache, both were limited mostly by memory copying.
- Total direct memory is capped by
, which defaults to the maximum heap size. Exceeding it gives-XX:MaxDirectMemorySize .OutOfMemoryError: Cannot reserve ... bytes of direct buffer memory
Choosing a buffer
| Situation | Use |
|---|---|
| Building or parsing a binary message in memory | ByteBuffer.allocateorder(...) |
| Long-lived buffer for sockets or files | One allocateDirect |
| Switch from writing to reading | flip() |
| Keep unread bytes and continue writing | compact() |
| Look at part of a buffer without copying | slice(index, length) |
| Read a value without moving position | Absolute getInt(index) |
| Random access to a large file | FileChannel.map |
| Off-heap memory over 2 GB or with explicit freeing |