Tuesday 12 January 2016

Java NIO Buffer

Java NIO Buffer 

Buffer is a block of data that is to be written to a channel or just read from a channel. It is an object that holds data and acts as an endpoint in a NIO channel. Buffer provides a formal mechanism to access data and tracks the read and write processes.
Buffer is one of the main differences between the old Java I/O and the NIO. Previously data is read directly from a stream or written directly into it. Now the data is read from a buffer or written into it. Channels are synonymous to streams in the NIO. To know more about NIO channel, please read the previous Java NIO Channel.

NIO Buffer Characteristics

  • Buffers are the basic building blocks of  Java NIO.
  • Buffers provides a fixed size container to read and write data.
  • Every buffer is readable, but only chosen buffers are writable.
  • Buffers are endpoints of Channels.
  • In a read-only buffer content is not mutable but, its mark, position and limit are mutable.
  • By default buffers are not thread-safe.

Buffer Types

There is a buffer type for each primitive type. All the buffer classes implement the Buffer interface. The most used buffer type is ByteBuffer. Following are the buffer types available in Java NIO package.
  • ByteBuffer
  • CharBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer
  • MappedByteBuffer

Buffer Capacity

Buffer is a fixed size type, we can store only a maximum of a “fixed amount” of data. That maximum fixed size is called capacity of the buffer. Once the buffer is full it should be cleared before writing to it. Once a capacity is set it never changes in its lifetime.

Buffer Limit

On write mode, limit is equal to the capacity of the buffer. On read mode, limit is one past the last filled index of the buffer. When the buffer is being written, the limit keeps incrementing. Limit of a buffer is always greater than or equal to zero and less than or equal to capacity. 0 <= limit <= capacity.

Buffer Position

Position points to the current location in buffer. When the buffer is created, position is set to zero. On write or read, the position is incremented to next index. Position is always set between zero and the limit of the buffer.

Buffer Mark

Mark is like setting a bookmark of the position in a buffer. When we mark() is called the current position is recorded and when reset() is called the marked position is restored.
http://www.spcjaipur.com/java-training-institute-in-jaipur.aspx

 

 

0 comments:

Post a Comment