Java- Java NIO

Java NIO(Non-blocking I/O)

The java.nio.file provide comprehensive support for file I/O and for accessing the default file system.

1) IO streams versus NIO blocks

  • NIO provides high-speed, block-oriented I/O.original I/O deals with data in streams, whereas NIO deals with data in blocks.

  • A block-oriented I/O system deals with data in blocks. Each operation produces or consumes a block of data in one step. Processing data by the block can be much faster than processing it by the (streamed) byte

2) Synchronous vs. Asynchronous IO

  • Java IO’s various streams are blocking or synchronous. That means, that when a thread invokes a read() or write(), that thread is blocked until there is some data to read, or the data is fully written.

  • In asynchronous IO, a thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the meantime. Usually these threads spend their idle time on when not blocked in IO calls, is usually performing IO on other channels in the meantime. That is, a single thread can now manage multiple channels of input and output

    public class ReadFileWithFixedSizeBuffer
    {
    public static void main(String[] args) throws IOException
    {
        RandomAccessFile aFile = new RandomAccessFile"test.txt", "r");
        FileChannel inChannel = aFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(inChannel.read(buffer) > 0)
        {
            buffer.flip();
            for (int i = 0; i < buffer.limit(); i++)
            {
                System.out.print((char) buffer.get());
            }
            buffer.clear(); // do something with the data and clear/compact it.
        }
        inChannel.close();
        aFile.close();
    }
    }
    
IO NIO
It is based on the Blocking I/O operation It is based on the Non-blocking I/O operation
It is Stream-oriented It is Buffer-oriented
Channels are not available Channels are available for Non-blocking I/O operation
Selectors are not available Selectors are available for Non-blocking I/O operation


Blocking vs. Non-blocking I/O

Blocking I/O
Blocking IO wait for the data to be write or read before returning. Java IO’s various streams are blocking. It means when the thread invoke a write() or read(), then the thread is blocked until there is some data available for read, or the data is fully written.

Non blocking I/O
Non blocking IO does not wait for the data to be read or write before returning. Java NIO non- blocking mode allows the thread to request writing data to a channel, but not wait for it to be fully written. The thread is allowed to go on and do something else in a mean time