One, foreword

Before I contact the NIO programming is less, so is weaker on the basis of this, the NIO, as an important module in the Java programming, can not master it very well, feel in Java is not enough, so, the next, the author will study the NIO programming, so, this series of articles will not involve the deep source code parsing, It is purely a learning course, and can also be understood as the author’s notes, recording the process of learning NIO, but also hope that this kind of article can be helpful to you who also want to master NIO programming.

What is NIO?

Java NIO(New IO) is an IO API that can replace the standard Java IO API (starting with Java 1.4). Java NIO provides a different way for IO to work than standard IO. NIO can be interpreted as non-blocking IO. The read and write of traditional IO can only block execution. The thread cannot do other things during the reading and writing of IO, such as calling socket.read().

IO and NIO

  • IO is byte stream and character stream oriented, while NIO is buffer-oriented.
  • IO is blocking mode, NIO is non-blocking mode
  • NIO has added the concept of a selector, through which you can listen to multiple channels.

4. NIO related concepts

Channel

Java NIO channels are like streams, but different:

You can read data from a channel and write data to a channel. But reads and writes to streams are usually one-way. Channels can be read and written asynchronously.

Data in a channel is always read to or written to from a Buffer.

The realization of the Channel

These are the implementations of the most important channels in Java NIO:

  • FileChannel: Reads and writes data from a file.

  • DatagramChannel: Read and write network data through UDP.

  • SocketChannel: Reads and writes data on the network through TCP.

  • ServerSocketChannel: Can listen for incoming TCP connections, just like a Web server. A SocketChannel is created for each incoming connection.

Buffer

A buffer is essentially a block of memory from which data can be written and then read. This chunk of memory is wrapped as a NIO Buffer object and provides a set of methods for easy access to the chunk of memory.

The main properties of a Buffer

attribute function
capacity capacity
position Pointer to the current position of the buffer, maximum capacity – 1
limit Buffer maximum read and write limits

Schematic diagram of buffer properties:

In write mode, limit is the same as Capacity, which indicates the maximum amount of data you can write. In read mode, limit is the same as Position, which indicates that you can read all the data you write.

Main categories of buffers

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

In fact, there is only a special MappedByteBuffer for receiving different data types. We will not learn it this time and learn about it later.

Five, the actual combat

We implemented a simple NIO program to understand the concepts described above, read files in folders, and then output them to the console.

 public static  void testNio(){
        try {
            RandomAccessFile rdf=new RandomAccessFile("E:\\nio\\niotest.txt"."rw"); // Use FileChannel in channel to read FileChannel from fileinChannel= rdf.getChannel(); // Set buffer size to 10 ByteBuffer buf= ByteBuffer. Allocate (10); // Read data from the channel into the buffer, return the number of bytes read int byteRead=inChannel.read(buf); // A value of -1 indicates that the data has been read.while(byteRead! Flip () {// Flip (); // Flip (); // Flip (); // If the buffer still has datawhile(buf.hasRemaining()){// Outputs a character system.out.print ((char) buf.get()); } // Clear the buffer buf.clear(); // continue to write the remaining data in the channel to buffer byteRead =inChannel.read(buf); } // Close the channel rdf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}Copy the code

I have niotest.txt on disk saying hello world, let’s see if the result is Hello World.

buf.flip()

If buf.flip() is commented out, the output is incorrect.

buf.hasRemaining()

  • Buffer reads 10 bytes of content, which is hello worl.

  • Buf.hasremaining () determines that the value is false, and clears the buffer directly (resetting position to 0 directly overwrites the content), and reads the rest of the content.

  • Finally, there is only one character d left to read. After reading, the contents of the buffer are as follows: dello worl.

  • Ello worl (postion=1)

Flip () : position = 0; position = 0; position = 0; position = 0; Reading the source code also confirmed my guess, the source code is as follows:

  public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }
Copy the code

reference

The JAVA NIO

Recommended reading

Java Lock ReentrantLock (part 1)

Java Lock ReentrantLock (part 2)

Java Lock ReentrantReadWriteLock