Article Directory
- Foreword
- Blocking and non-blocking
- Synchronous and asynchronous
- JAVA BIO 包
- Java NIO
- NIO core object of the Channel
- NIO core object of Buffer
- Buffer read and write operations of FIG.
- The main achievement of class Buffer
- The principle Buffer
- Buffer state value change map
- NIO core object of Selector
- BIO and NIO comparative summary
Foreword
- Given the very next question is now the industry's most circumstances
AIO
(for me), just about summed up this interviewBIO
withNIO
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 oneI/O
, which means thatread/write
the 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 issuesI/O
a 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 upCPU
control. 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 aError
case 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, inNone-Block I/O
the user threads need to constantly ask if the kernel data ready, will always occupy theCPU
resources
Synchronous and asynchronous
- Synchronization is based on asynchronous
应用程序
andOS
processingI/O
event-employed,
同步 :
Is an application need to participate inI/O
the read and write operations, and in the processingI/O
time of an event, the kernel must block waiting for data ready in a method above, in this case, whether it isread/write
operating, we can not perform the following operation异步 :
AllI/O
read and write operations to theOS
process, the application only needs to wait for the notification, in this case, we can do other things, does not need to block waiting forI/O
the completion of the operation, whenI/O
after 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 entireIO
operation is carried out how, just to initiate a request, when receiving the success notification kernel returned, it meansI/O
the operation has been completed.
JAVA BIO 包
Java NIO
NIO network model diagram
NIO core object of the Channel
Channel
Can be used for reading and writing operations,read/write
data are operated byBuffer
time 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
NIO core object of Buffer
Buffer
Is a container, a continuous array is inNIO
, all of the read / write data operations are byBuffer
Buffer read and write operations of FIG.
The main achievement of class Buffer
The principle Buffer
Buffer
It is a special array, which is built a number of mechanisms to track and record changes of state of the buffer, if usedBuffer#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
Data bufferTest.txt file
Buffer state value change map
NIO core object of Selector
NIO
IsNone-Block I/O
basedReactor
mode works inI/O
not blocked when calling.Selector
IsNIO
the core classes,Selector
it 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
Selector
obtaining appropriate inSelectionKey
the same time fromSelectionKey
can be found in a specific time and the time of occurrence occurredSelectableChannel
data sent by the client to acquire the- Use
NIO
of non-blockingI/O
write server processing program is divided into the following steps
- To
Selector
register an event object of interest- From the
Selector
get events of interest in the object- The appropriate treatment for different events
BIO and NIO comparative summary
面向流和面向缓冲 :
BIO
Stream oriented, each read from the means of six1-n
bytes, 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.NIO
The channel is non-blocking, a request to write data to the user threadChannel
, but it need not wait for it to fully written, the user thread may also do other operations typically user threadNone-Block I/O
idle time for other channels performingI/O
operation, so that a single thread can managen
input / output channels
选择器 :
Java NIO
TheSelector
may be a thread to monitor then
channels, and may register a plurality ofChannel
simultaneously using oneSelector
and 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 managen
channels
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,