• NIO基础-Selector,Nio概念


    4. 网络编程

    4.1 非阻塞 vs 阻塞

    阻塞
    • 阻塞模式下,相关方法都会导致线程暂停
      • ServerSocketChannel.accept 会在没有连接建立时让线程暂停
      • SocketChannel.read 会在没有数据可读时让线程暂停
      • 阻塞的表现其实就是线程暂停了,暂停期间不会占用 cpu,但线程相当于闲置
    • 单线程下,阻塞方法之间相互影响,几乎不能正常工作,需要多线程支持
    • 但多线程下,有新的问题,体现在以下方面
      • 32 位 jvm 一个线程 320k,64 位 jvm 一个线程 1024k,如果连接数过多,必然导致 OOM,并且线程太多,反而会因为频繁上下文切换导致性能降低
      • 可以采用线程池技术来减少线程数和线程上下文切换,但治标不治本,如果有很多连接建立,但长时间 inactive,会阻塞线程池中所有线程,因此不适合长连接,只适合短连接

    测试阻塞模式

    服务端代码

    @Slf4j
    public class Server {
    
        public static void main(String[] args) throws IOException {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            //创建服务器
            ServerSocketChannel ssc = ServerSocketChannel.open();
            //绑定监听端口
            ssc.bind(new InetSocketAddress(8088));
            List<SocketChannel> channels = new ArrayList<>();
            while (true) {
                log.debug("connecting...");
                //accept 建立与客户端连接, SocketChannel 用来与客户端之间通信
                SocketChannel sc = ssc.accept();//阻塞
                log.debug("connected... {}", sc);
                channels.add(sc);
                for (SocketChannel channel : channels) {
                    //接收客户端数据
                    log.debug("before read... {}", channel);
                    channel.read(buffer);//阻塞
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("after read...{}", channel);
                }
    
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    客户端代码

    public class Client {
        public static void main(String[] args) throws IOException {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("localhost",8088));
            System.out.println("123");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    测试流程:启动服务端,给客户端打上断点,然后控制台发送消息,可以看到此时服务端已经打印出消息了,再次发送消息,服务端没反应,原因是ssc.accept()是阻塞的,再开启一个客户端,可以看到服务端打印了第二次发的消息

    非阻塞
    • 非阻塞模式下,相关方法都会不会让线程暂停
      • 在 ServerSocketChannel.accept 在没有连接建立时,会返回 null,继续运行
      • SocketChannel.read 在没有数据可读时,会返回 0,但线程不必阻塞,可以去执行其它 SocketChannel 的 read 或是去执行 ServerSocketChannel.accept
      • 写数据时,线程只是等待数据写入 Channel 即可,无需等 Channel 通过网络把数据发送出去
    • 但非阻塞模式下,即使没有连接建立,和可读数据,线程仍然在不断运行,白白浪费了 cpu
    • 数据复制过程中,线程实际还是阻塞的(AIO 改进的地方)

    服务器端代码,客户端代码不变

    @Slf4j
    public class Server {
    
        public static void main(String[] args) throws IOException {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            //创建服务器
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);//配置accept非阻塞
            //绑定监听端口
            ssc.bind(new InetSocketAddress(8088));
            List<SocketChannel> channels = new ArrayList<>();
            while (true) {
                //accept 建立与客户端连接, SocketChannel 用来与客户端之间通信
                SocketChannel sc = ssc.accept();//非阻塞,线程还会继续运行,如果没有连接建立,但sc是null
                if (sc != null) {
                    log.debug("connected... {}", sc);
                    sc.configureBlocking(false);//配置read非阻塞
                    channels.add(sc);
                }
                for (SocketChannel channel : channels) {
                    //接收客户端数据
                    int read = channel.read(buffer);//非阻塞,线程仍然会继续运行,如果没有读到数据,read 返回 0
                    if (read > 0) {
                        buffer.flip();
                        debugRead(buffer);
                        buffer.clear();
                        log.debug("after read...{}", channel);
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    测试流程:启动服务端,给客户端打上断点,连续启动两个客户端,发现服务端控制台都打印了连接信息,可证明ssc.accept()是非阻塞的了,再用任意一个客户端控制台发消息,发两次,可以看到服务端控制台打印了消息,可证明channel.read也是非阻塞的了

    4.2 Selector

    在这里插入图片描述

    好处

    • 一个线程配合 selector 就可以监控多个 channel 的事件,事件发生线程才去处理。避免非阻塞模式下所做无用功
    • 让这个线程能够被充分利用
    • 节约了线程的数量
    • 减少了线程上下文切换
    创建

    通过调用Selector.open()方法创建一个Selector

    Selector selector = Selector.open();

    向Selector注册通道

    为了将Channel和Selector配合使用,必须将channel注册到selector上。通过SelectableChannel.register()方法来实现,

    channel.configureBlocking(false);
    SelectionKey key = channel.register(selector, 绑定事件);
    
    • 1
    • 2
    • channel 必须工作在非阻塞模式
    • FileChannel 没有非阻塞模式,因此不能配合 selector 一起使用
    • 绑定的事件类型可以有
      • connect - 客户端连接成功时触发
      • accept - 服务器端成功接受连接时触发
      • read - 数据可读入时触发,有因为接收能力弱,数据暂不能读入的情况
      • write - 数据可写出时触发,有因为发送能力弱,数据暂不能写出的情况
    监听 Channel 事件

    可以通过下面三种方法来监听是否有事件发生,方法的返回值代表有多少 channel 发生了事件

    方法1,阻塞直到绑定事件发生

    int count = selector.select();
    
    • 1

    方法2,阻塞直到绑定事件发生,或是超时(时间单位为 ms)

    int count = selector.select(long timeout);
    
    • 1

    方法3,不会阻塞,也就是不管有没有事件,立刻返回,自己根据返回值检查是否有事件

    int count = selector.selectNow();
    
    • 1
    💡 select 何时不阻塞
    • 事件发生时
      • 客户端发起连接请求,会触发 accept 事件
      • 客户端发送数据过来,客户端正常、异常关闭时,都会触发 read 事件,另外如果发送的数据大于 buffer 缓冲区,会触发多次读取事件
      • channel 可写,会触发 write 事件
      • 在 linux 下 nio bug 发生时
    • 调用 selector.wakeup()
    • 调用 selector.close()
    • selector 所在线程 interrupt

    4.3 处理 accept 事件

    客户端代码不变,服务端代码如下

    @Slf4j
    public class Server {
    
        public static void main(String[] args) throws IOException {
            //创建selector
            Selector selector = Selector.open();
            //创建服务端,并设置非阻塞
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));
    
            //建立selector和channel的联系(channel注册到selector上)
            SelectionKey sscKey = ssc.register(selector, 0, null);
            //只关注accept类型的事件
            sscKey.interestOps(SelectionKey.OP_ACCEPT);
            log.info("sscKey:{}", sscKey);
    
            while (true) {
                //没有事件就阻塞,有事件就继续向下运行
                //有事件未处理时,不会阻塞,所有要么处理,要么阻塞
                selector.select();
                //处理时间,selectedKeys包含了所有发生的事件
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    log.info("key:{}", key);
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    log.info("sc:{}", sc);
                    //key.cancel();
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    💡 事件发生后能否不处理

    事件发生后,要么处理,要么取消(cancel),不能什么都不做,否则下次该事件仍会触发,这是因为 nio 底层使用的是水平触发

    💡 cancel 的作用

    cancel 会取消注册在 selector 上的 channel,并从 keys 集合中删除 key 后续不会再监听事件

    4.3 处理 read 事件

    @Slf4j
    public class Server {
    
        public static void main(String[] args) throws IOException {
            //创建selector
            Selector selector = Selector.open();
            //创建服务端,并设置非阻塞
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));
    
            //建立selector和channel的联系(channel注册到selector上)
            SelectionKey sscKey = ssc.register(selector, 0, null);
            //只关注accept类型的事件
            sscKey.interestOps(SelectionKey.OP_ACCEPT);
            log.info("sscKey:{}", sscKey);
    
            while (true) {
                //没有事件就阻塞,有事件就继续向下运行
                //有事件未处理时,不会阻塞,所有要么处理,要么阻塞
                selector.select();
                //处理时间,selectedKeys包含了所有发生的事件
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    // 处理key 时,要从 selectedKeys集合中删除,否则下次处理就会有问题
                    iter.remove();
                    log.info("key:{}", key);
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        //建立连接并设置非阻塞
                        SocketChannel sc = channel.accept();
                        sc.configureBlocking(false);
                        //注册到selector上,只关注read事件
                        SelectionKey scKey = sc.register(selector, 0, null);
                        scKey.interestOps(SelectionKey.OP_READ);
                        log.info("sc:{}", sc);
                    } else if (key.isReadable()) {
                        try {
                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            int read = channel.read(buffer);//客户端正常断开,read方法返回值-1
                            if (read == -1) {
                                log.info("客户端断开连接");
                                key.cancel();
                            } else {
                                buffer.flip();
                                debugRead(buffer);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            //因为客户端异常断开了,因此需要将key 取消,从 selector 的 keys 合中真正删除 key
                            key.cancel();
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    💡 为何要 iter.remove()

    因为 select 在事件发生后,就会将相关的 key 放入 selectedKeys 集合,但不会在处理完后从 selectedKeys 集合中移除,需要我们自己编码删除。例如

    • 第一次触发了 ssckey 上的 accept 事件,没有移除 ssckey
    • 第二次触发了 sckey 上的 read 事件,但这时 selectedKeys 中还有上次的 ssckey ,在处理时因为没有真正的 serverSocket 连上了,就会导致空指针异常
    💡 什么时候要 cancel

    客户端断开时会产生一个读事件,如果不处理,就会一直执行,所以需要cancel取消这个key

    • 正常断开:通过read方法检测客户端正常断开,取消key
    • 异常断开:try-catch捕获异常,防止客户端异常断开造成服务端挂掉
    处理消息的边界

    在这里插入图片描述

    • 一种思路是固定消息长度,数据包大小一样,服务器按预定长度读取,缺点是浪费带宽
    • 另一种思路是按分隔符拆分,缺点是效率低
    • TLV 格式,即 Type 类型、Length 长度、Value 数据,类型和长度已知的情况下,就可以方便获取消息大小,分配合适的 buffer,缺点是 buffer 需要提前分配,如果内容过大,则影响 server 吞吐量
      • Http 1.1 是 TLV 格式
      • Http 2.0 是 LTV 格式

    在这里插入图片描述
    服务端代码

    @Slf4j
    public class Server {
        private static void split(ByteBuffer source) {
            source.flip();
            for (int i = 0; i < source.limit(); i++) {
                // 找到一条完整消息
                if (source.get(i) == '\n') {
                    int length = i + 1 - source.position();
                    // 把这条完整消息存入新的 ByteBuffer
                    ByteBuffer target = ByteBuffer.allocate(length);
                    // 从 source 读,向 target 写
                    for (int j = 0; j < length; j++) {
                        target.put(source.get());
                    }
                    debugAll(target);
                }
            }
            source.compact(); // 0123456789abcdef  position 16 limit 16
        }
    
        public static void main(String[] args) throws IOException {
            //创建selector
            Selector selector = Selector.open();
            //创建服务端,并设置非阻塞
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));
    
            //建立selector和channel的联系(channel注册到selector上)
            SelectionKey sscKey = ssc.register(selector, 0, null);
            //只关注accept类型的事件
            sscKey.interestOps(SelectionKey.OP_ACCEPT);
            log.info("sscKey:{}", sscKey);
    
            while (true) {
                //没有事件就阻塞,有事件就继续向下运行
                //有事件未处理时,不会阻塞,所有要么处理,要么阻塞
                selector.select();
                //处理时间,selectedKeys包含了所有发生的事件
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    // 处理key 时,要从 selectedKeys集合中删除,否则下次处理就会有问题
                    iter.remove();
                    log.info("key:{}", key);
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        //建立连接并设置非阻塞
                        SocketChannel sc = channel.accept();
                        sc.configureBlocking(false);
                        // 将一个 byteBuffer 作为附件关联到 selectionKey 上
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        SelectionKey scKey = sc.register(selector, 0, buffer);
                        scKey.interestOps(SelectionKey.OP_READ);
                        log.info("sc:{}", sc);
                    } else if (key.isReadable()) {
                        try {
                            SocketChannel channel = (SocketChannel) key.channel();
                            // 获取 selectionKey 上关联的附件
                            ByteBuffer buffer = (ByteBuffer) key.attachment();
                            int read = channel.read(buffer);//客户端正常断开,read方法返回值-1
                            if (read == -1) {
                                log.info("客户端断开连接");
                                key.cancel();
                            } else {
                                split(buffer);
                                // 需要扩容
                                if (buffer.position()==buffer.limit()){
                                    ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                    buffer.flip();
                                    newBuffer.put(buffer);
                                    key.attach(newBuffer);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            //因为客户端异常断开了,因此需要将key 取消,从 selector 的 keys 合中真正删除 key
                            key.cancel();
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84

    客户端代码

    public class Client {
        public static void main(String[] args) throws IOException {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("localhost",8080));
            sc.write(StandardCharsets.UTF_8.encode("0123456789abcdef3333\n"));
            System.out.println("123");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    ByteBuffer 大小分配
    • 每个 channel 都需要记录可能被切分的消息,因为 ByteBuffer 不能被多个 channel 共同使用,因此需要为每个 channel 维护一个独立的 ByteBuffer
    • ByteBuffer 不能太大,比如一个 ByteBuffer 1Mb 的话,要支持百万连接就要 1Tb 内存,因此需要设计大小可变的 ByteBuffer
      • 一种思路是首先分配一个较小的 buffer,例如 4k,如果发现数据不够,再分配 8k 的 buffer,将 4k buffer 内容拷贝至 8k buffer,优点是消息连续容易处理,缺点是数据拷贝耗费性能,参考实现 http://tutorials.jenkov.com/java-performance/resizable-array.html
      • 另一种思路是用多个数组组成 buffer,一个数组不够,把多出来的内容写入新的数组,与前面的区别是消息存储不连续解析复杂,优点是避免了拷贝引起的性能损耗

    4.5 处理 write 事件

    一次无法写完例子
    • 非阻塞模式下,无法保证把 buffer 中所有数据都写入 channel,因此需要追踪 write 方法的返回值(代表实际写入字节数)
    • 用 selector 监听所有 channel 的可写事件,每个 channel 都需要一个 key 来跟踪 buffer,但这样又会导致占用内存过多,就有两阶段策略
      • 当消息处理器第一次写入消息时,未写完才将 channel 注册到 selector 上
      • selector 检查 channel 上的可写事件,如果所有的数据写完了,就取消 channel 的注册
      • 如果不取消,会每次可写均会触发 write 事件
    💡 write 为何要取消

    在I/O多路复用中,写事件(Write Event)的生成通常与操作系统的套接字缓冲区状态有关。如果缓冲区有足够的空间,就会生成写事件。应用程序需要监测这些写事件,并在有数据可写入时将数据写入套接字,然后取消写事件以避免无限触发。这是一种有效的机制,确保数据写入不会阻塞,同时避免不必要的CPU负载。

    服务端代码

    public class WriteServer {
        public static void main(String[] args) throws IOException {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
            ssc.bind(new InetSocketAddress(8080));
            while (true) {
                selector.select();
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isAcceptable()) {
                        SocketChannel sc = ssc.accept();
                        sc.configureBlocking(false);
                        SelectionKey sckey = sc.register(selector, 0, null);
                        sckey.interestOps(SelectionKey.OP_READ);
                        // 1. 向客户端发送大量数据
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < 8000000; i++) {
                            sb.append("a");
                        }
                        ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
    
                        // 2. 返回值代表实际写入的字节数
                        int write = sc.write(buffer);
                        System.out.println(write);
    
                        // 3. 判断是否有剩余内容
                        if (buffer.hasRemaining()) {
                            // 4. 关注可写事件   1                     4
                            sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);
    //                        sckey.interestOps(sckey.interestOps() | SelectionKey.OP_WRITE);
                            // 5. 把未写完的数据挂到 sckey 上
                            sckey.attach(buffer);
                        }
                    } else if (key.isWritable()) {
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        SocketChannel sc = (SocketChannel) key.channel();
                        //当调用sc.write(buffer)时,写入的数据会从ByteBuffer中清除
                        int write = sc.write(buffer);
                        System.out.println(write);
                        //debugAll(buffer);
                        // 6. 清理操作
                        if (!buffer.hasRemaining()) {
                            key.attach(null); // 需要清除buffer
                            key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);//不需关注可写事件
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    客户端代码

    public class WriteClient {
        public static void main(String[] args) throws IOException {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("localhost", 8080));
    
            // 3. 接收数据
            int count = 0;
            while (true) {
                ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
                count += sc.read(buffer);
                System.out.println(count);
                buffer.clear();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.6 更进一步

    💡 利用多线程优化

    现在都是多核 cpu,设计时要充分考虑别让 cpu 的力量被白白浪费

    前面的代码只有一个选择器,没有充分利用多核 cpu,如何改进呢?

    分两组选择器

    • 单线程配一个选择器,专门处理 accept 事件
    • 创建 cpu 核心数的线程,每个线程配一个选择器,轮流处理 read 事件

    在这里插入图片描述

    boss只处理连接,worker只处理读写,而且是多个worker同时工作

    服务端代码

    @Slf4j
    public class MultiServer {
    
        public static void main(String[] args) throws IOException {
            Thread.currentThread().setName("boss");
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(8080));
            ssc.configureBlocking(false);
    
            Selector boss = Selector.open();
            ssc.register(boss, SelectionKey.OP_ACCEPT, null);
    
            Worker worker = new Worker("worker-0");
            worker.register();
            while (true) {
                boss.select();
                Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isAcceptable()) {
                        SocketChannel sc = ssc.accept();
                        sc.configureBlocking(false);
                        log.info("connected...,{}", sc.getRemoteAddress());
                        //关联自定义selector
                        log.info("before register...,{}", sc.getRemoteAddress());
                        sc.register(worker.selector, SelectionKey.OP_READ, null);
                        log.info("after register...,{}", sc.getRemoteAddress());
                    }
                }
            }
        }
    
        static class Worker implements Runnable {
            private Thread thread;
            private Selector selector;
            private String name;
            private volatile boolean start = false;
    
            public Worker(String name) {
                this.name = name;
            }
    
            //初始化线程和selector
            public void register() throws IOException {
                //保证只执行一次,下一个客户端连接的时候再调用时,不会执行
                if (!start) {
                    //selector初始化要放在线程初始化前,否则空指针
                    selector = Selector.open();
                    thread = new Thread(this, name);
                    thread.start();
                    start = true;
                }
            }
    
            @Override
            public void run() {
                while (true) {
                    try {
                        selector.select();
                        Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                        while (iter.hasNext()) {
                            SelectionKey key = iter.next();
                            iter.remove();
                            if (key.isReadable()) {
                                ByteBuffer buffer = ByteBuffer.allocate(16);
                                SocketChannel channel = (SocketChannel) key.channel();
                                log.info("read...,{}", channel.getRemoteAddress());
                                channel.read(buffer);
                                buffer.flip();
                                debugAll(buffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80

    客户端代码

    public class MultiClient {
    
        public static void main(String[] args) throws IOException {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("localhost",8080));
            sc.write(StandardCharsets.UTF_8.encode("123456789"));
            System.out.println("123");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    先启动服务端,再启动客户端,可以看到结果有问题
    在这里插入图片描述

    优化服务端代码:

    @Slf4j
    public class MultiServer {
    
        public static void main(String[] args) throws IOException {
            Thread.currentThread().setName("boss");
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(8080));
            ssc.configureBlocking(false);
    
            Selector boss = Selector.open();
            ssc.register(boss, SelectionKey.OP_ACCEPT, null);
    
            Worker worker = new Worker("worker-0");
            while (true) {
                boss.select();
                Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isAcceptable()) {
                        SocketChannel sc = ssc.accept();
                        sc.configureBlocking(false);
                        log.info("connected...,{}", sc.getRemoteAddress());
                        //关联自定义selector
                        log.info("before register...,{}", sc.getRemoteAddress());
                        worker.register(sc);
                        log.info("after register...,{}", sc.getRemoteAddress());
                    }
                }
            }
        }
    
        static class Worker implements Runnable {
            private Thread thread;
            private Selector selector;
            private String name;
            private volatile boolean start = false;
            private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
    
            public Worker(String name) {
                this.name = name;
            }
    
            //初始化线程和selector
            public void register(SocketChannel sc) throws IOException {
                //保证只执行一次,下一个客户端连接的时候再调用时,不会执行
                if (!start) {
                    //selector初始化要放在线程初始化前,否则空指针
                    selector = Selector.open();
                    thread = new Thread(this, name);
                    thread.start();
                    start = true;
                }
                //将任务放入队列中,在另一个线程中指定位置取出执行
                queue.add(() -> {
                    try {
                        sc.register(selector, SelectionKey.OP_READ, null);
                    } catch (ClosedChannelException e) {
                        e.printStackTrace();
                    }
                });
                //selector.wakeup() 的作用是在调用它后,立即将阻塞在 select() 上的线程唤醒,
                // 即使没有事件发生。这可以用来中断 select() 方法的阻塞,
                // 以便在需要的时候立即重新注册或取消注册事件,而不必等待 select() 方法的自然返回。
                selector.wakeup();
            }
    
            @Override
            public void run() {
                while (true) {
                    try {
                        selector.select();
                        Runnable task = queue.poll();
                        if (Objects.nonNull(task)) {
                            task.run();
                        }
                        Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                        while (iter.hasNext()) {
                            SelectionKey key = iter.next();
                            iter.remove();
                            if (key.isReadable()) {
                                ByteBuffer buffer = ByteBuffer.allocate(16);
                                SocketChannel channel = (SocketChannel) key.channel();
                                log.info("read...,{}", channel.getRemoteAddress());
                                channel.read(buffer);
                                buffer.flip();
                                debugAll(buffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96

    另一种实现,只需在register方法中执行selector.wakeup();即可

    public void register(SocketChannel sc) throws IOException {
        //保证只执行一次,下一个客户端连接的时候再调用时,不会执行
        if (!start) {
            //selector初始化要放在线程初始化前,否则空指针
            selector = Selector.open();
            thread = new Thread(this, name);
            thread.start();
            start = true;
        }
        //selector.wakeup() 的作用是在调用它后,立即将阻塞在 select() 上的线程唤醒,
        // 即使没有事件发生。这可以用来中断 select() 方法的阻塞,
        // 以便在需要的时候立即重新注册或取消注册事件,而不必等待 select() 方法的自然返回。
        selector.wakeup();
        sc.register(selector, SelectionKey.OP_READ, null);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    多线程的一种使用,让一段代码在另一个线程指定位置执行

    private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
    
    //放入队列中,等待执行
    queue.add(() -> {
        try {
            sc.register(selector, SelectionKey.OP_READ, null);
        } catch (ClosedChannelException e) {
            e.printStackTrace();
        }
    });
    
    //指定位置取出执行
    Runnable task = queue.poll();
    if (Objects.nonNull(task)) {
        task.run();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    增加多个worker处理事件

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
    
        Selector boss = Selector.open();
        ssc.register(boss, SelectionKey.OP_ACCEPT, null);
    
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        AtomicInteger index = new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.info("connected...,{}", sc.getRemoteAddress());
                    //关联自定义selector
                    log.info("before register...,{}", sc.getRemoteAddress());
                    workers[index.getAndIncrement() % workers.length].register(sc);
                    log.info("after register...,{}", sc.getRemoteAddress());
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    💡 如何拿到 cpu 个数
    • Runtime.getRuntime().availableProcessors() 如果工作在 docker 容器下,因为容器不是物理隔离的,会拿到物理 cpu 个数,而不是容器申请时的个数
    • 这个问题直到 jdk 10 才修复,使用 jvm 参数 UseContainerSupport 配置, 默认开启

    5. NIO vs BIO

    5.1 stream vs channel

    • stream 不会自动缓冲数据,channel 会利用系统提供的发送缓冲区、接收缓冲区(更为底层)
    • stream 仅支持阻塞 API,channel 同时支持阻塞、非阻塞 API,网络 channel 可配合 selector 实现多路复用
    • 二者均为全双工,即读写可以同时进行

    5.2 IO 模型

    同步阻塞、同步非阻塞、同步多路复用、异步阻塞(没有此情况)、异步非阻塞

    • 同步:线程自己去获取结果(一个线程)
    • 异步:线程自己不去获取结果,而是由其它线程送结果(至少两个线程)

    当调用一次 channel.read 或 stream.read 后,会切换至操作系统内核态来完成真正数据读取,而读取又分为两个阶段,分别为:

    • 等待数据阶段

    • 复制数据阶段
      在这里插入图片描述

    • 阻塞 IO
      在这里插入图片描述

    • 非阻塞 IO
      在这里插入图片描述

    • 多路复用
      在这里插入图片描述

    • 信号驱动

    • 异步 IO
      在这里插入图片描述

    • 阻塞 IO vs 多路复用
      在这里插入图片描述
      在这里插入图片描述

    5.3 零拷贝

    传统 IO 问题

    传统的 IO 将一个文件通过 socket 写出

    File f = new File("helloword/data.txt");
    RandomAccessFile file = new RandomAccessFile(file, "r");
    
    byte[] buf = new byte[(int)f.length()];
    file.read(buf);
    
    Socket socket = ...;
    socket.getOutputStream().write(buf);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    内部工作流程是这样的:

    在这里插入图片描述

    1. java 本身并不具备 IO 读写能力,因此 read 方法调用后,要从 java 程序的用户态切换至内核态,去调用操作系统(Kernel)的读能力,将数据读入内核缓冲区。这期间用户线程阻塞,操作系统使用 DMA(Direct Memory Access)来实现文件读,其间也不会使用 cpu

      DMA 也可以理解为硬件单元,用来解放 cpu 完成文件 IO

    2. 内核态切换回用户态,将数据从内核缓冲区读入用户缓冲区(即 byte[] buf),这期间 cpu 会参与拷贝,无法利用 DMA

    3. 调用 write 方法,这时将数据从用户缓冲区(byte[] buf)写入 socket 缓冲区,cpu 会参与拷贝

    4. 接下来要向网卡写数据,这项能力 java 又不具备,因此又得从用户态切换至内核态,调用操作系统的写能力,使用 DMA 将 socket 缓冲区的数据写入网卡,不会使用 cpu

    可以看到中间环节较多,java 的 IO 实际不是物理设备级别的读写,而是缓存的复制,底层的真正读写是操作系统来完成的

    • 用户态与内核态的切换发生了 3 次,这个操作比较重量级
    • 数据拷贝了共 4 次
    NIO 优化

    通过 DirectByteBuf

    • ByteBuffer.allocate(10) HeapByteBuffer 使用的还是 java 内存
    • ByteBuffer.allocateDirect(10) DirectByteBuffer 使用的是操作系统内存

    在这里插入图片描述

    大部分步骤与优化前相同,不再赘述。唯有一点:java 可以使用 DirectByteBuf 将堆外内存映射到 jvm 内存中来直接访问使用

    • 这块内存不受 jvm 垃圾回收的影响,因此内存地址固定,有助于 IO 读写
    • java 中的 DirectByteBuf 对象仅维护了此内存的虚引用,内存回收分成两步
      • DirectByteBuf 对象被垃圾回收,将虚引用加入引用队列
      • 通过专门线程访问引用队列,根据虚引用释放堆外内存
    • 减少了一次数据拷贝,用户态与内核态的切换次数没有减少

    进一步优化(底层采用了 linux 2.1 后提供的 sendFile 方法),java 中对应着两个 channel 调用 transferTo/transferFrom 方法拷贝数据
    在这里插入图片描述

    1. java 调用 transferTo 方法后,要从 java 程序的用户态切换至内核态,使用 DMA将数据读入内核缓冲区,不会使用 cpu
    2. 数据从内核缓冲区传输到 socket 缓冲区,cpu 会参与拷贝
    3. 最后使用 DMA 将 socket 缓冲区的数据写入网卡,不会使用 cpu

    可以看到

    • 只发生了一次用户态与内核态的切换
    • 数据拷贝了 3 次

    进一步优化(linux 2.4)

    在这里插入图片描述

    1. java 调用 transferTo 方法后,要从 java 程序的用户态切换至内核态,使用 DMA将数据读入内核缓冲区,不会使用 cpu
    2. 只会将一些 offset 和 length 信息拷入 socket 缓冲区,几乎无消耗
    3. 使用 DMA 将 内核缓冲区的数据写入网卡,不会使用 cpu

    整个过程仅只发生了一次用户态与内核态的切换,数据拷贝了 2 次。所谓的【零拷贝】,并不是真正无拷贝,而是再不会拷贝重复数据到 jvm 内存中,零拷贝的优点有

    • 更少的用户态与内核态的切换
    • 不利用 cpu 计算,减少 cpu 缓存伪共享
    • 零拷贝适合小文件传输
    文件 AIO

    先来看看 AsynchronousFileChannel

    @Slf4j
    public class AioFileChannel {
        public static void main(String[] args) throws IOException {
            try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)) {
                // 参数1 ByteBuffer
                // 参数2 读取的起始位置
                // 参数3 附件
                // 参数4 回调对象 CompletionHandler
                ByteBuffer buffer = ByteBuffer.allocate(16);
                log.debug("read begin...");
                channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override // read 成功
                    public void completed(Integer result, ByteBuffer attachment) {
                        log.debug("read completed...{}", result);
                        attachment.flip();
                        debugAll(attachment);
                    }
                    @Override // read 失败
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        exc.printStackTrace();
                    }
                });
                log.debug("read end...");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.in.read();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    结果

    10:27:31 [DEBUG] [main] c.i.n.a.AioFileChannel - read begin...
    10:27:31 [DEBUG] [main] c.i.n.a.AioFileChannel - read end...
    10:27:31 [DEBUG] [Thread-3] c.i.n.a.AioFileChannel - read completed...14
    +--------+-------------------- all ------------------------+----------------+
    position: [0], limit: [14]
             +-------------------------------------------------+
             |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
    +--------+-------------------------------------------------+----------------+
    |00000000| 31 32 33 34 35 36 37 38 39 30 61 62 63 64 00 00 |1234567890abcd..|
    +--------+-------------------------------------------------+----------------+
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    可以看到

    • 响应文件读取成功的是另一个线程 Thread-3
    • 主线程并没有 IO 操作阻塞
    💡 守护线程

    默认文件 AIO 使用的线程都是守护线程,所以最后要执行 System.in.read() 以避免守护线程意外结束

  • 相关阅读:
    java的面向对象基础(1) —— 封装
    【GUI】Python图形界面(三)
    【OpenCv】相机标定介绍及python/c++实现
    【深度学习笔记】计算机视觉——单发多框检测(SSD)
    HTTP流量神器Goreplay核心源码详解
    Qemu 启动无法交互的处理方法
    K8s中的RBAC(Role-Based Access Control)
    Java 泛型中的通配符
    关于content-type的理解
    【Text2SQL】评估 LLM 的 Text2SQL 能力
  • 原文地址:https://blog.csdn.net/qq_42665745/article/details/133791107