Talking about BIO in Java Network Programming

Java BIO (synchronous blocking I/O)

A client request must be executed using a thread. If it is executed in a single thread, it will cause its request to wait.

How BIO works:

One connection one thread processing

Insert picture description here

Code demo

ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
    
    
            Socket socket = serverSocket.accept();
            try {
    
    
                new Thread() {
    
    
                    @Override
                    public void run() {
    
    
                        // 开始执行 业务处理
                    }
                }.start();
            } catch (Exception e) {
    
    
                e.printStackTrace();
                if (socket != null) {
    
    
                    socket.close();
                }
            }
        }

This BIO mode has a big disadvantage. Each time the server receives a request, it creates a thread and the JVM allocates a memory. If there is too much concurrency, threads will be created frequently, which will cause a lot of overhead to the server. GC is not collected in time, it will cause memory leak or memory overflow

Implementation of BIO thread pool

Insert picture description here

Code demo

ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(100, 160,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(128));
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
    
    
            Socket socket = serverSocket.accept();
            try {
    
    
                poolExecutor.execute(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        // 执行业务请求
                    }
                });
            } catch (Exception e) {
    
    
                e.printStackTrace();
                if (socket != null) {
    
    
                    socket.close();
                }
            }
        }

The thread pool implementation can avoid memory leaks or memory overflows caused by frequent thread creation. But there are also disadvantages: because of the maximum number of threads set by the thread pool, if there are too many concurrent threads, if the threads of the thread pool are not idle, they will wait until there are idle threads.Obviously, high concurrency cannot be satisfied.

Guess you like

Origin blog.csdn.net/liuqi199707/article/details/109002113