1 NIO Introduce

Java NIO Full name java non-blocking IO , Refer to JDK What's new API. from JDK1.4 Start ,Java Provides a series of improved inputs / New features of output , Is referred to as NIO( namely New IO), It's synchronous and non blocking .

1. NIO There are three core parts :Channel( passageway ),Buffer( buffer ), Selector( Selectors )

2. NIO yes Buffer oriented programming . The data is read into a buffer , Move back and forth in the buffer if needed , This increases the flexibility of the process , It can be used to provide non blocking high scalability network

3. Java NIO Non blocking mode of , To cause a thread to send a request or read data from a channel , But it can only get data that is currently available , If there is no data available , You will get nothing , Instead of keeping threads blocked , So until the data becomes readable , The thread can continue to do other things . So is nonblocking writing , A thread requests to write some data to a channel , But you don't have to wait for it to write completely , This thread can do other things at the same time . Easy to understand :NIO It can handle multiple operations with one thread . Suppose there is 10000 Please come here , According to the actual situation , Can allocate 50 perhaps 100 Threads to handle . It's not like the block before IO like that , Obligatory distribution 10000 individual

2 NIO and BIO Comparison

1. BIO Processing data as a stream , and NIO Processing data as a buffer , buffer I/O Is more efficient than flow I/O Much higher

2. BIO It's blocked ,NIO It's non blocking

3. BIO Operation based on byte stream and character stream , and NIO be based on Channel( passageway ) and Buffer( buffer ) To operate , Data is always read from the channel into the buffer , Or write from buffer to channel .Selector( Selectors ) Used to listen for multiple channel events ( such as : Connection request , Data arrival, etc ), So a single thread can listen to multiple client channels

3 NIO Schematic diagram of three core principles

A picture describes NIO Of Selector 、 Channel and Buffer The relationship between

image.png

1. Every channel There will be one Buffer

2. Selector Corresponding to a thread , A thread corresponds to multiple channel( Connect )

3. Every channel All registered to Selector On selector

4. Selector Keep polling to see Channel Events on the , Events are channels Channel A very important concept

5. Selector According to different events , Complete different processing operations

6. Buffer It's just a memory block , At the bottom is an array

7. Data is read and written by Buffer, This and BIO , BIO It's either an input stream , Or the output stream , It can't be two-way , however NIO Of Buffer It can be read or written , channel It's two-way .


4 buffer (Buffer)

Basic introduction

buffer (Buffer): Buffer is essentially a block of memory that can read and write data , It can be understood as an array , The object provides a set of methods , Memory blocks can be used more easily ,, Buffer objects have built-in mechanisms , Ability to track and record buffer state changes .Channel Provides access to data from the network , But the data read or written must go through Buffer.

image.png


Buffer Commonly used API Introduce

Buffer Classes and subclasses

stay NIO in ,Buffer Is a top-level parent class , It's an abstract class , Class hierarchy diagram , Common buffers correspond to byte,short, int, long,float,double,char 7 Kind of .

image.png

Buffer object creation

image.png

Sample code :


package com.lagou.buffer;

import java.nio.ByteBuffer;

/**

* Create buffer

*/

public class CreateBufferDemo {

  public static void main(String[] args) {

    //1. Create a buffer of the specified length , With ByteBuffer For example

    ByteBuffer byteBuffer = ByteBuffer.allocate(5);

    for (int i = 0; i < 5; i++) {

      System.out.println(byteBuffer.get());

}

    // This call will report an error -- The next time I read the buffer, I will focus on

    //System.out.println(byteBuffer.get());

    //2. Create a buffer with content

    ByteBuffer wrap = ByteBuffer.wrap("lagou".getBytes());

    for (int i = 0; i < 5; i++) {

      System.out.println(wrap.get());

   }

 }

}

3. Buffer objects add data

image.png

The illustration :

   image.png

Sample code :

package com.lagou.buffer;

import java.nio.ByteBuffer;

/**

* Add buffer

*/

public class PutBufferDemo {

  public static void main(String[] args) {

    //1. Create a buffer of the specified length , With ByteBuffer For example

    ByteBuffer byteBuffer = ByteBuffer.allocate(10);

    System.out.println(byteBuffer.position());//0 Gets the location of the current index

    System.out.println(byteBuffer.limit());//10 Which index can be manipulated at most

    System.out.println(byteBuffer.capacity());//10 Returns the total length of the buffer

    System.out.println(byteBuffer.remaining());//10 How many more can operate

    // Modify the current index position

    //byteBuffer.position(1);

    // Which index position can be modified at most

    //byteBuffer.limit(9);

    //System.out.println(byteBuffer.position());//1 Gets the location of the current index

    //System.out.println(byteBuffer.limit());//9 Which index can be manipulated at most

    //System.out.println(byteBuffer.capacity());//10 Returns the total length of the buffer

//System.out.println(byteBuffer.remaining());//8 How many more can operate

    // Add a byte

    byteBuffer.put((byte) 97);

    System.out.println(byteBuffer.position());//1 Gets the location of the current index

    System.out.println(byteBuffer.limit());//10 Which index can be manipulated at most

    System.out.println(byteBuffer.capacity());//10 Returns the total length of the buffer

    System.out.println(byteBuffer.remaining());//9 How many more can operate

    // Add an array of bytes

    byteBuffer.put("abc".getBytes());

    System.out.println(byteBuffer.position());//4 Gets the location of the current index

    System.out.println(byteBuffer.limit());//10 Which index can be manipulated at most

    System.out.println(byteBuffer.capacity());//10 Returns the total length of the buffer

    System.out.println(byteBuffer.remaining());//6 How many more can operate

    // An error will be reported when the addition exceeds the length of the buffer

    byteBuffer.put("012345".getBytes());

    System.out.println(byteBuffer.position());//10 Gets the location of the current index

    System.out.println(byteBuffer.limit());//10 Which index can be manipulated at most

    System.out.println(byteBuffer.capacity());//10 Returns the total length of the buffer

    System.out.println(byteBuffer.remaining());//0 How many more can operate

    System.out.println(byteBuffer.hasRemaining());// false Can there be any operation

Array

    // If the buffer is full , You can adjust position The position can be written repeatedly , This will override pairs that were previously indexed

The expected value is

    byteBuffer.position(0);

    byteBuffer.put("012345".getBytes());

 }

}

4 Buffer object reads data   

image.png

The illustration :flip() Method

image.png

The illustration :clear() Method

image.png

The sample code :

package com.lagou.buffer;

import java.nio.ByteBuffer;

/**

* Read data from buffer

*/

public class GetBufferDemo {

  public static void main(String[] args) {

    //1. Create a buffer of the specified length

    ByteBuffer allocate = ByteBuffer.allocate(10);

    allocate.put("0123".getBytes());

    System.out.println("position:" + allocate.position());//4

    System.out.println("limit:" + allocate.limit());//10

    System.out.println("capacity:" + allocate.capacity());//10

    System.out.println("remaining:" + allocate.remaining());//6

    // Toggle read mode

    System.out.println(" Reading data --------------");

    allocate.flip();

    System.out.println("position:" + allocate.position());//4

    System.out.println("limit:" + allocate.limit());//10


System.out.println("capacity:" + allocate.capacity());//10

    System.out.println("remaining:" + allocate.remaining());//6

    for (int i = 0; i < allocate.limit(); i++) {

      System.out.println(allocate.get());

   }

    // After reading . Continue reading will report an error , exceed limit value

    //System.out.println(allocate.get());

    // Read the specified index byte

    System.out.println(" Read the specified index byte --------------");

    System.out.println(allocate.get(1));

    System.out.println(" Read multiple bytes --------------");

    // Duplicate read

  allocate.rewind();

    byte[] bytes = new byte[4];

  allocate.get(bytes);

    System.out.println(new String(bytes));

    // Convert buffer to byte array and return

    System.out.println(" Convert buffer to byte array and return --------------");

    byte[] array = allocate.array();

    System.out.println(new String(array));

    // Switch write mode , Override the value of the previous index location

    System.out.println(" Write mode --------------");

    allocate.clear();

    allocate.put("abc".getBytes());

    System.out.println(new String(allocate.array()));

 }

}

matters needing attention :

1. capacity: Capacity ( length )limit: boundaries ( Can read at most / Where to write )posotion: Location ( read / Which index to write )

2. Before getting the data in the buffer , Need to call flip Method

3. Before writing data again , Need to call clear Method , But the data hasn't disappeared yet , Wait to write data again , It's covered before it disappears .