慢慢说 IO 模型:改造型 BIO

小Q:前边说了 BIO 的缺点,我们有没有什么方法对其改进呢?

慢慢:为了解决前面提到的 BIO 的每一个连接都需要一个线程处理的问题,有人提出了一个解决方案,用线程池的方式对线程进行管理,防止由于海量并发接入导致线程耗尽,实现系统的可控。


小Q:懂了懂了,赶快上代码。

服务端

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8080);   // 创建服务端连接
            ServerHandlerExecutePool executor = new ServerHandlerExecutePool(50, 10000);  // 创建 I/O 任务线程
            Socket socket = null;
            while (true) {
                socket = server.accept();  // 阻塞,直到有连接建立
                executor.execute(new ServerHandler(socket));  // 在线程池中获取一个线程处理连接
            }
        } finally {
            if (server != null) {
                server.close();
                server = null;
            }
            if (socket != null) {
                socket.close();
                socket = null;
            }
        }
    }
}

线程池:

public class ServerHandlerExecuePool {
    private ExecutorService executor;
    
    // maxPoolSize 最大线程数,queueSize 阻塞队列的最大空间
    public ServerHandlerExecuePool(int maxPoolSize, int queueSize) {
        // 初始化线程数,最大线程数,空闲线程存活时间,存活单位,阻塞队列
        executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize));
    }
    
    public execute(Runnable task) {
        executor.execute(task);
    }
}

执行连接

public class ServerHandler implements Runnable {
    private Socket socket;
    
    public ServerHandler(Socket socket) {
        this.socket = socket;
    }
    
    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            String currentTime = null;
            String body = null;
            while (true) {
                body = in.readLine();
                if (body == null)
                    break;
                out.println(body);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

客户端

public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        BufferReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket("127.0.0.1", 8080);   // 建立连接,发起连接请求
            in = new BufferReader(new InputStreamReader(socket.getInputStream()));  // 监听此缓冲区
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println("QUERY TIME ORDER");   // 向服务器端发送指令
            String s = in.readLine();   // 从缓冲区中获取数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅退出
            if (out != null) {
                try {
                    out.close();  // 释放缓冲区
                    out = null;
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                
            }
            if (in != null) {
                in.close();  // 释放缓冲区
                in = null;
            }
            if (this.socket != null) {
                try {
                    this.socket.close();  // 关闭连接
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                this.socket = null;
            }
        }
    }
}

小Q:改造后的 BIO 有什么缺点吗?

慢慢:改在后的 BIO 提高了线程数量的可控性,但还是不满足长连接的需求场景。因为一旦建立多个长连接,线程池的线程也都被占用,此时其他的连接只能防止阻塞队列中。由于 TCP 连接的特性,发送方在收不到响应时会重复发送请求,迟迟收不到响应时会认为网络拥堵,将逐渐减少滑档窗口的大小,直到关闭滑动窗口,使网络崩溃。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慢慢编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值