Brief analysis of blocking and non blocking of IO model in Java network programming

  • 2021-11-13 07:42:34
  • OfStack

Directory 1. Blocking I/O model 2. Non-blocking I/O model

1. Blocking I/O model

The blocking IO model is a common IO model where client-side blocking occurs while reading and writing data. The workflow for blocking the IO model is:

1.1 After the user thread sends out the IO request, the kernel will check whether the data is ready. At this time, the user thread 1 directly blocks and waits for the memory data to be ready;

1.2 After the memory data is ready, the kernel copies the data to the user thread and returns the I/O execution results to the user thread. At this time, the user thread will release the blocking state and start processing the data.

A typical example of the blocking I/O model is data=socket. read (). If the kernel data is not ready, the Socket thread will block in reado until the kernel data is ready.

2. Non-blocking I/O model

The non-blocking I/O model means that after a user thread initiates an operation, it can immediately get a result returned by the kernel without blocking. If the kernel returns fase, the kernel data is not ready and the I/O operation needs to be initiated later. 1 Once the data in the kernel is ready and the request from the user thread is received again, the kernel immediately copies the data to the user thread and notifies the user thread of the copy result.
In the non-blocking IO model, the user thread needs to constantly ask whether the kernel data is ready. When the memory data is not ready, the user thread can handle other tasks, and can immediately obtain the data and execute corresponding operations after the kernel data is ready. A typical non-blocking IO model is as follows:


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Test7 {
    public static void main(String[] args) throws IOException {
        ServerSocket socket=new ServerSocket();
        while(true){
            Socket data=socket.accept();
            if (data!=null) {
                // Data processing completed 
                break;}
            else {
                // The kernel data is not processed, and other thread services are carried out 
            }
        }
    }
}

The above is the Java network programming IO model blocking and non-blocking brief analysis of the details, more about the java model IO blocking and non-blocking information please pay attention to other related articles on this site!


Related articles: