Video in progress

What are position, limit and capacity in an NIO ByteBuffer, and how does flip() change them?

capacity is the total size of the buffer, position is the next read/write location, and limit is the boundary you can't go past. flip() switches from write mode to read mode: limit = position, position = 0.

📖 Answer

Picture the buffer as three pointers over a single array.

ByteBuffer buf = ByteBuffer.allocate(8);   // pos=0 lim=8 cap=8
buf.put((byte) 1).put((byte) 2).put((byte) 3); // pos=3 lim=8

buf.flip();                                 // pos=0 lim=3
while (buf.hasRemaining()) {
    System.out.println(buf.get());          // 1, 2, 3
}

buf.clear();                                // pos=0 lim=8, ready for writing again

Other methods:

  • clear() does not erase the data, it only resets the pointers;
  • compact() moves the unread remainder to the start and continues writing in the remaining space. You need it for a message that arrived partially from a socket;
  • rewind() sets position = 0 and leaves the limit alone: for re-reading;
  • mark() / reset(): remember a position and return to it.

Forgetting flip() is the most common mistake in NIO. When you write to a channel, zero bytes go out, or the wrong part goes out, and the code "runs but sends nothing".