Java NIO – Channels and Memory mapping

Channel Classes

  • Channel– A channel represents a connection to a file, socket or any other component that can perform IO operations. A channel reads or writes data to a byte buffer. Channels are generally thread safe. A channel may be specified to be read only or both readable and writable.
  • ReadableByteChannel – A ReadableByteChannel permits read operation on a buffer, allowing only one thread to read at a time.
  • WritableByteChannel – A WritableByteChannel permits write operation on a buffer, allowing only one thread to read at a time.
  • ByteChannel – A ByteChannel extends both ReadableByteChannel and WritableByteChannel and allows both read and write.
  • SeekableByteChannel – A SeekableByteChannel extends ByteChannel and allows to maintain and modify the current position on the underlying entity to which it is connected. It has methods to get the size of the underlying entity or truncate it to a given size, if permitted.
  • GatheringByteChannel-A GatheringByteChannel is used to write data from multiple buffers into a single channel.
  • ScatteringByteChannel-A ScatteringByteChannel is used to read data from a channel into multiple buffers.

File Channel

A FileChannel is used to read and write data to a file. It implements seekableByteChannel, ScatteringByteChannel and GatheringByteChannel. It is possible to map a region of file directly into memory. Data can be transferred to another channel or from another channel using the transferTo(..) and transferFrom(..) methods. These methods use the underlying optimization of the operating system. File locking can be applied to manage access between multiple processes. The methods are thread safe and a thread that wishes to modify the position may be blocked until another thread is acting upon the file.

Scatter Read using File Channel

Data from a File Channel can be read into multiple buffers. This is known as a scatter read. Here’s and example demonstrating a scatter read.

Scatter Write using File Channel

we can write the bytes back to the file using a scattering write. The filechannel was created on the inputstream so the channel is only readable but not writable. we create a filechannel from an output stream

Reading Huge Files using Memory Mapped Buffer

Java NIO allows reading huge files directly from the memory. i.e. The file need not be loaded into the JVM. All reads and writes on the byte buffer happen direclty on the file.

Leave a Comment