当前位置:网站首页>Block, non block, multiplexing, synchronous, asynchronous, bio, NiO, AIO
Block, non block, multiplexing, synchronous, asynchronous, bio, NiO, AIO
2022-06-23 16:13:00 【InfoQ】
1 Blocking and non blocking
1.1 Blocking

- CPU Read data from disk to kernel buffer .
- CPU Copy data from the kernel buffer to the user buffer .
1.2 Non blocking

1.3 IO Multiplexing


1.3.1 select
- select The parameter array passed in will be modified , This is for a function that needs to be called many times , It's very unfriendly .
- select If any one sock(I/O stream) There's data ,select Just going back to , But I won't tell you it's that sock There's data on , I can only search by myself .
- select Only surveillance 1024 A link .
- select Not thread safe , If you put one sock Add to select, And then suddenly another thread finds this sock no need , To withdraw , This select Don't support .
1.3.2 poll
- poll Removed 1024 Link restrictions .
- poll By design, the incoming array is no longer modified .
1.3.3 epoll
- epoll Now it's thread safe .
- epoll Now not only tell you sock Data in the group , I will also tell you which sock There's data , You don't have to find it yourself .
- epoll Kernel state manages all kinds of IO File descriptor , Previously, user mode sent all file descriptors to kernel mode , Then kernel state is responsible for filtering and returning available arrays , Now? epoll All file descriptors exist in kernel mode , You don't need to transfer file descriptors when querying .
1.3.4 Comparison between the three

1.4 asynchronous IO

【 Article Welfare 】 In addition, Xiaobian also sorted out some C++ Back-end development interview questions , Teaching video , Back end learning roadmap for free , You can add what you need :
Click to join the learning exchange group ~
Group file sharing
Xiaobian strongly recommends C++ Back end development free learning address :
C/C++Linux Server development senior architect /C++ Background development architect

2 Synchronous and asynchronous
2.1 Sync
- Synchronous blocking : At this point, a thread maintains a connection , The thread completes the whole process from data reading and writing to processing , When reading and writing data, the thread is blocked .
- Synchronous nonblocking : Nonblocking means that after a user thread makes a read request , Read requests do not block the current user thread , However, the user thread should continue to actively judge whether the data is ready OK 了 . At this point, it will still block waiting for the kernel to copy data to the user process . He's in sync with BIO The difference is using a connection to wait all the way

2.2 asynchronous

2.3 Synchronous versus asynchronous
3 Java IO
- BIO: Synchronous blocking IO.
- NIO: Synchronous nonblocking IO.
- AIO: Asynchronous non-blocking IO.
3.1 BIO

- Use a separate thread to maintain a socket Connect , As the number of connections increases , Put some pressure on the virtual machine .
- Using streams to read data , The flow is blocked , When there is no readability / When data can be written , Thread waiting , It wastes resources .
3.1.1 BIO Examples
public class Constant {
public static final String HOST = "127.0.0.1";
public static final int PORT = 8080;
}public class ClientMain {
public static void main(String[] args) {
// Opening service
System.out.println(" Opening service , Listening port :" + Constant.PORT);
new Thread(new ServerThread()).start();
// Build a socket client , Initiate request
System.out.println(" client , Request connection , And send data ");
try {
Socket socket = new Socket(Constant.HOST,Constant.PORT);
// Turn on new thread processing socket Connect
new Thread(new ClientProcessThread(socket)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}// Turn on the service listener thread , When a connection request is received , Open a new thread to process
public class ServerThread implements Runnable{
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(Constant.PORT);
while (true){
Socket socket = serverSocket.accept();
new Thread(new ServerProcessThread(socket)).start();
// Start a new thread to process the connection request
}
} catch (IOException e) {
e.printStackTrace();
}
}
}import java.io.*;
import java.net.Socket;
/**
* After the server receives the connection request , The thread that processes the request , Blocking type IO
*/
public class ServerProcessThread implements Runnable {
private Socket socket;
public ServerProcessThread(Socket socket){
this.socket = socket;
}
@Override
public void run() {
// Get client data , And write back
// Waiting response
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = "";
String requestStr = "";
System.out.println(" Data from the client :"); // Read client data
while((line = bufferedReader.readLine()) != null){
requestStr += line;
System.out.println(line);
}
// Send data from the server to the client
Writer writer = new OutputStreamWriter(socket.getOutputStream());
writer.write("data from server " + requestStr + "\r\n");
writer.flush();
writer.close();
bufferedReader.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}/**
* Maintain the client socket Connecting threads , Blocking type IO
*/
public class ClientProcessThread implements Runnable {
private Socket socket;
public ClientProcessThread(Socket socket){
this.socket = socket;
}
@Override
public void run() {
// Writing data , Waiting response , Output response
String requestStr = "data from client \r\n";
try {
Writer writer = new OutputStreamWriter(socket.getOutputStream());
writer.write(requestStr);
writer.flush();
socket.shutdownOutput();
// Waiting response
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
System.out.println(" Response from the server :");
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
writer.close();
bufferedReader.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.2 NIO

- You don't have to create threads for each connection .
- Data read and write non blocking .
- selector:Selector Allow a single thread to handle multiple Channel. If your app has multiple connections open ( passageway ), But the traffic for each connection is very low , Use Selector It will be very convenient . To use Selector, Direction Selector register Channel, And then call him. select Method , This method will block until an event is ready on a registered channel . Once this method returns , Threads can handle these events , Examples of events come in with new connections , Data reception, etc .
- Channel: Basically all IO stay NIO All from one Channel Start .Channel It's kind of like a stream , Data can be obtained from channelreadTo buffer, You can also get it from bufferWriteTo channel.
- Buffer: Buffer is essentially a block of memory that can read and write data , It can be understood as a container object ( With array ), The object provides a set of methods , Can use memory block more easily , Buffer objects have built-in mechanisms , It can track and record the state transition of buffer ,Channel Provide documentation from , Network access to data , But the data read or written must pass through Buffer.
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannelByteBuffer
CharBuffer
FloatBuffer
IntBuffer
LongBuffer
ShortBuffer
3.3 AIO
Reference material

边栏推荐
- 【TcaplusDB知识库】Tmonitor单机安装指引介绍(二)
- Advanced development - generic entry basic class test
- 513. Find Bottom Left Tree Value
- 安全舒适,全新一代奇骏用心诠释老父亲的爱
- [tcapulusdb knowledge base] Introduction to new models of tcapulusdb
- 进阶开发阶段-势若悬丝的加粗开始. 现在的一小步,明年的一大步
- Array's own method
- How is it cheaper to open a stock account? Is it safe to open an account online now?
- freemark 使用ftl文件 生成word
- 医学影像分割的网站
猜你喜欢

安全舒适,全新一代奇骏用心诠释老父亲的爱

阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一文搞定
![[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (II)](/img/6d/8b1ac734cd95fb29e576aa3eee1b33.png)
[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (II)
NLP 论文领读|改善意图识别的语义表示:有监督预训练中的各向同性正则化方法

Block, non block, multiplexing, synchronous, asynchronous, bio, NiO, AIO

stylegan2:analyzing and improving the image quality of stylegan
![[tcapulusdb knowledge base] Introduction to tmonitor system upgrade](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[tcapulusdb knowledge base] Introduction to tmonitor system upgrade

window远程桌面连接互传文件加速小技巧

matlab: 如何从一些数据里知道是由哪些数据相加得出一个已知数

Interpreting the 2022 agile coaching industry status report
随机推荐
Charge pump principle handout, how is the voltage "pumped"?
万字攻略,详解腾讯面试(T1-T9)核心技术点,面试题整理
【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)
TCP协议三次握手和四次挥手抓包分析
基金开户是有什么风险?开户安全吗
SaaS 云工具,产业互联网下的变革利器
Apple iPhone, Samsung mobile phone and other electronic products began to enter Russia through parallel import channels
Thread pool
《ThreadLocal》
Uniapp sends picture messages to Tencent instant messaging Tim
TCP protocol notes
SSRS页面配置Postgresql data source的方法
Array's own method
医学影像分割的网站
Generating binary search balanced tree [using tree recursion]
OutputDebugString使用说明以及异常处理
Does the enterprise want to use the MES system? These conditions have to be met
npm install 问题解决(nvm安装与使用)
Sleuth + Zipkin
HBuilderX-Light 主题能不能加个批注功能?