Java Reference
In-Depth Information
The limit is the index position of the first element that should not be read or written. Thus, elements
can be read or written starting with the element at position , and up to and including the element at
limit-1 . Thus if you want to fill all the elements in a buffer, the position must be at zero since this is
where the first data item will go, and the limit must be equal to the capacity since the last data item has
to be stored at the last element in the buffer, which is capacity-1 .
A buffer's position and limit are used for determining what elements are involved in a read or write
operation executed by a channel. How they affect I/O operations is easier to understand if we take a
specific example. Let's first consider an operation that writes data from the buffer to a file.
capacity = 10
empty
empty
empty
empty
element
element
element
element
element
element
position = 0
limit = 6
When a file write operation is executed by a channel using a given buffer, elements from the buffer will
be written to the file starting at the index specified by the position. Successive elements will be written
to the file up to, and including, the element at index position limit-1 . For a read operation, data that is
read from the file is stored in a buffer starting at the element index given by the buffer position.
Elements will continue to be read, assuming they are available from the file, up to the index position
limit-1 . Thus when you want to write all the data from a buffer, the limit will have to be equal to the
capacity. In this case the limit will be an index value that is one beyond the index value for the last
element in the buffer, so limit-1 will refer to the last element.
The position and limit are involved when you load data into a buffer or retrieve data from it. The
position specifies where the next element should be inserted in a buffer or retrieved from it. As we shall
see, you will usually have the position automatically incremented to point to the next available position
when you insert or extract elements in a buffer. The limit acts as a constraint to indicate where the data
in a buffer ends, a bit like an end-of-file marker. You cannot insert or extract elements beyond the
position specified by the limit.
Since a buffer's position is an index, it must be greater than or equal to zero. You can also deduce that it
must also be less than or equal to the limit. Clearly, the limit cannot be greater than the capacity of a
buffer. Otherwise, we could be trying to write elements to positions beyond the end of the buffer.
However, as we have seen, it can be equal to it. These relationships can be expressed as:
0 • position • limit • capacity
As a general rule, if your code attempts to do things directly or indirectly that result in these
relationships being violated, an exception will be thrown.
Search WWH ::




Custom Search