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:

Java NIO buffer layout

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:

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.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.