Java interview summary of the IO, NIO articles - you still could not tell silly IO and NIO do


Foreword

  • Given the very next question is now the industry's most circumstances AIO(for me), just about summed up this interview BIOwithNIO

Blocking and non-blocking

  • When accessing data in the process, whether the data is ready for processing way, when the data is not ready when ready:
    • Block IO:Is a traditional one I/O, which means that read/writethe phenomenon will occur in the process of blocking, often after only deal with other things prospective data shellfish need to wait in the buffer, otherwise would have been blocked. When a user thread issues I/Oa request after that, the kernel checks to see if the data buffer is ready, if not ready, the user thread will wait to enter the data ready and blocked user thread to give up CPUcontrol. after the data is ready, the kernel buffer data area are copied to the user thread and return the results to the user thread, the thread will unblock user.
    • None-Block I/O:When the user threads access the data buffer, regardless of whether the data is ready to directly get the results, do not wait, if it is a Errorcase of it until the data is not ready, will visit again slow data buffer, once the kernel data is ready, and when the user receives a request thread again, it will copy the data to the user thread and return, in None-Block I/Othe user threads need to constantly ask if the kernel data ready, will always occupy the CPUresources

Synchronous and asynchronous

  • Synchronization is based on asynchronous 应用程序and OSprocessing I/Oevent-employed,
    • 同步 :Is an application need to participate in I/Othe read and write operations, and in the processing I/Otime of an event, the kernel must block waiting for data ready in a method above, in this case, whether it is read/writeoperating, we can not perform the following operation
    • 异步 :All I/Oread and write operations to the OSprocess, the application only needs to wait for the notification, in this case, we can do other things, does not need to block waiting for I/Othe completion of the operation, when I/Oafter the completion of the operation will give us a notification. 【例: Ajax】, From the core point of view, when after receiving an asynchronous read will return immediately, indicating that the read request has been sent successfully, it will not produce a thread blocked for the user. then, the kernel will wait for the data is ready, and then copy the data to the user thread, also that is the thread completely without the user knowing the entire IOoperation is carried out how, just to initiate a request, when receiving the success notification kernel returned, it means I/Othe operation has been completed.

JAVA BIO 包

Here Insert Picture Description

Java NIO

NIO network model diagram

Here Insert Picture Description

NIO core object of the Channel

  • ChannelCan be used for reading and writing operations, read/writedata are operated by Buffertime for processing the object, will read operation when data is read into the buffer, the write operation will obtain the data from the buffer

Channel main implementation class

Here Insert Picture Description

NIO core object of Buffer

  • BufferIs a container, a continuous array is in NIO, all of the read / write data operations are byBuffer

Buffer read and write operations of FIG.

Here Insert Picture Description

The main achievement of class Buffer

Here Insert Picture Description

The principle Buffer

  • BufferIt is a special array, which is built a number of mechanisms to track and record changes of state of the buffer, if used Buffer#read()/flip()/get()/clear()during the method, will lead to changes in buffer status
	// Invariants: mark <= position <= limit <= capacity
    private int mark = -1;
    private int position = 0;
    private int limit;
    private int capacity;

Test code Buffer state value

package com.cj.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: CaoJun
 * @Create: 2020-03-11 06:03
 **/
public class BufferTest {

    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream(new File("C:\\Users\\john\\Desktop\\nio\\bufferTest.txt"));
        // 获取文件操作管道
        FileChannel fileChannel = fis.getChannel();
        // 分配大小为 10 的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        printBufferStatus("初始化缓冲区大小 ", byteBuffer);

        // 读取缓冲区
        fileChannel.read(byteBuffer);
        printBufferStatus("调用 read() 方法", byteBuffer);

        // 锁定操作的范围
        byteBuffer.flip();
        printBufferStatus("调用 flip() 方法", byteBuffer);

        // 判断文件中是否有数据
        while (byteBuffer.remaining() > 0) {
            byteBuffer.get();
        }
        printBufferStatus("调用 get()  方法", byteBuffer);

        // 清除缓冲区中的数据
        byteBuffer.clear();
        printBufferStatus("调用 clear() 方法", byteBuffer);

        // 关闭管道
        fileChannel.close();

    }

    /**
     * 打印缓冲区状态
     */
    private static void printBufferStatus(String step, Buffer buffer) {
        System.out.print(step + " : ");
        //容量,数组大小
        System.out.print("capacity: " + buffer.capacity() + ", ");
        //当前操作数据所在的位置,也可以叫做游标
        System.out.print("position: " + buffer.position() + ", ");
        //锁定值,flip,数据操作范围索引只能在 position - limit 之间
        System.out.println("limit: " + buffer.limit() + "\r\n");
    }

}

Buffer status value of the test results

Here Insert Picture Description

Data bufferTest.txt file

Here Insert Picture Description

Buffer state value change map

Here Insert Picture Description

NIO core object of Selector

  • NIOIs None-Block I/Obased Reactormode works in I/Onot blocked when calling. SelectorIs NIOthe core classes, Selectorit can detect whether there are more registered on the channel event occurs, if an event occurs, you get events and each event the corresponding response processing, so that you can use only one thread can manage through the channels. so only when operatively coupled to read and write events, call the method will read and write operations, thus greatly reducing system overhead, and do not create a thread for each connection, do not maintain multiple threads and avoids the overhead of context switching between multiple threads.
  • When the figure below regardless of read / write and so any registration occurred at a time, from Selectorobtaining appropriate in SelectionKeythe same time from SelectionKeycan be found in a specific time and the time of occurrence occurred SelectableChanneldata sent by the client to acquire the
  • Use NIOof non-blocking I/Owrite server processing program is divided into the following steps
    • To Selectorregister an event object of interest
    • From the Selectorget events of interest in the object
    • The appropriate treatment for different events

Here Insert Picture Description

BIO and NIO comparative summary

  • 面向流和面向缓冲 :
    • BIOStream oriented, each read from the means of six 1-nbytes, to know all the bytes read, and the read byte is not cached, the data stream can not move in the back and forth, moves back and forth if desired data read from the stream, it is necessary first cache them into a buffer,
    • NIO Oriented buffered, means that each first-read data buffer, when moved back and forth may be needed in the buffer, thus increasing the flexibility of the process
  • 阻塞和非阻塞 :
    • BIO The flow is blocked, means that the user thread for each read / write operation time will be blocked until there is some data to be read, or write a book complete data at the same time the user thread can not do other operations, If no data is available under the case, nothing will get, rather than to ensure that thread is blocked, so until the data can be read before the next state of the thread can do other operations.
    • NIOThe channel is non-blocking, a request to write data to the user thread Channel, but it need not wait for it to fully written, the user thread may also do other operations typically user thread None-Block I/Oidle time for other channels performing I/Ooperation, so that a single thread can manage ninput / output channels
      选择器 :
    • Java NIOThe Selectormay be a thread to monitor the nchannels, and may register a plurality of Channelsimultaneously using one Selectorand then use a separate thread to select channels which are already processed can be input or selected channel is ready to write this selection mechanism will make a separate thread to easily manage nchannels
IO model BIO NIO
communication Stream-oriented Buffer for
deal with Blocking IO (Multi Thread) Non-blocking IO (Reactor)
trigger no Selector (Round)

  • Okay, BIO and NIO are finished right now. Nothing is impossible as long as you are willling to do it,
Published 23 original articles · won praise 3 · Views 1156

Guess you like

Origin blog.csdn.net/weixin_38251871/article/details/104788614