The Layout of a NIO buffer
The following diagram shows the basic anatomy of a NIO buffer. For the sake of argument,
we'll label it from the point of view of writing data to the buffer, but the
layout is essentially the same for reading:
A buffer is an area in memory. In many cases– though not necessarily–
a NIO buffer object wraps around an underlying Java byte array or portion of a byte array.
Each box in the diagram thus represents a byte position in memory, and in the underlying byte array if any.
The position is a reasonably obvious concept: it represents the
next offset in the buffer to read or write data. Specifically:
- if we call one of the buffer
object's read or write methods (actually get() and put()) without specifying
an offset, then the operation will take place at the buffer's current position;
position will be updated automatically after the read or write.
Buffer offsets always start at zero, although it is possible to wrap
a buffer around a section of a byte array, so that offset 0 of the buffer might actually
map to some other offset of the underlying byte array.
The limit is the maximum position that we currently want to read or write.
Typically this would be the same as the buffer's capacity but it can be set to some lesser
position as required.
This facility can be useful when we want to process only part of a buffer. But it does mean that we need to be
careful in some cases that we know whether we are referring to this "virtual" limit or the "actual" end of the buffer.
Next: different buffer classes
Now we have an overview of what a buffer generally looks like, it's time to start looking
at some of the specific buffer classes available in NIO.