• 关于Java NIO的的思考


    关于BIO和NIO的概念和区别什么的就不在这里说明了,这片文章主要是关于通过Java nio来实现同步非阻塞模型,我们首先要搞明白此处的同步非阻塞只是针对IO,而不是读取数据之后的处理操作,然后就是有几个前置的知识要明确:

    1. 同步强调的是应用程序需要自己主动去询问操作系统内核,对数据进行读写,目前linux只支持同步,windows支持异步,异步则指的是应用程序本身不需要主动的去询问操作系统数据读写情况,数据准备好之后操作系统会通知应用程序来处理数据

    2. 阻塞指的是应用程序在等待客户端连接函数读取数据的时候表现出来的,当没有客户端连接和数据过来的时候,应用程序代码会阻塞住,无法往下执行,而异步则是应用程序在调用系统函数,比如accept和read的时候,一定会有一个返回值,应用程序会根据这个返回值来决定如何处理,而阻塞的时候,调用系统函数,比如accept和read的时候,如果没有数据,就不会有返回值

    我们先来看一段代码:

    1. import java.net.InetSocketAddress;
    2. import java.nio.ByteBuffer;
    3. import java.nio.channels.ServerSocketChannel;
    4. import java.nio.channels.SocketChannel;
    5. import java.util.LinkedList;
    6. import java.util.List;
    7. import java.util.concurrent.TimeUnit;
    8. public class NioServer {
    9. public static void main(String[] args) throws Exception {
    10. ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    11. //服务端非阻塞
    12. serverSocketChannel.configureBlocking(false);
    13. serverSocketChannel.bind(new InetSocketAddress(8888));
    14. List clients = new LinkedList<>();
    15. while (true) {
    16. TimeUnit.SECONDS.sleep(1);
    17. SocketChannel client = serverSocketChannel.accept();
    18. if (null == client) {
    19. System.err.println("没有新的客户端连接.....");
    20. } else {
    21. //客户端非阻塞
    22. client.configureBlocking(false);
    23. System.err.println(client.socket());
    24. clients.add(client);
    25. }
    26. ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
    27. for (SocketChannel socketChannel : clients) {
    28. int num = socketChannel.read(byteBuffer);
    29. if (num > 0) {
    30. byteBuffer.flip();
    31. byte[] bytes = new byte[byteBuffer.limit()];
    32. byteBuffer.get(bytes);
    33. String b = new String(bytes);
    34. System.err.println(b);
    35. byteBuffer.clear();
    36. }
    37. }
    38. }
    39. }
    40. }

     这是一个基本的NIO同步非阻塞模型,它的问题就是对于连接和读取数据都在一个线程里面去处理的,当连接数量多了之后,性能会急剧下降,可能大家会想到把数据处理丢到一个线程池里面去处理,也就是for循环的那一段,确实这样可以提高效率,但是这样指标不治本,这个代码最根本的问题就在于,这个for循环里面的int num = socketChannel.read(byteBuffer);这一句,这一句代码每次都会涉及到一次系统调用,也就是会有一次用户态和内核态的切换过程,那么为了解决这个问题,就演化出了多路复用器模型,也就是下面的代码

    1. import java.io.IOException;
    2. import java.net.InetSocketAddress;
    3. import java.nio.ByteBuffer;
    4. import java.nio.channels.SelectionKey;
    5. import java.nio.channels.Selector;
    6. import java.nio.channels.ServerSocketChannel;
    7. import java.nio.channels.SocketChannel;
    8. import java.util.Iterator;
    9. public class AsyncNonBlockingServer {
    10. private Selector selector;
    11. private ServerSocketChannel serverChannel;
    12. private ByteBuffer buffer;
    13. public AsyncNonBlockingServer(int port) throws IOException {
    14. // 创建选择器和服务器通道
    15. selector = Selector.open();
    16. serverChannel = ServerSocketChannel.open();
    17. serverChannel.bind(new InetSocketAddress(port));
    18. serverChannel.configureBlocking(false);
    19. // 注册服务器通道到选择器,并注册接收连接事件
    20. serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    21. buffer = ByteBuffer.allocate(1024);
    22. }
    23. public void start() throws IOException {
    24. System.out.println("Server started.");
    25. while (true) {
    26. // 阻塞等待事件发生
    27. selector.select();
    28. // 处理事件
    29. Iterator keyIterator = selector.selectedKeys().iterator();
    30. while (keyIterator.hasNext()) {
    31. SelectionKey key = keyIterator.next();
    32. keyIterator.remove();
    33. if (key.isAcceptable()) {
    34. // 接收连接事件
    35. handleAccept(key);
    36. } else if (key.isReadable()) {
    37. // 可读事件
    38. handleRead(key);
    39. }
    40. }
    41. }
    42. }
    43. private void handleAccept(SelectionKey key) throws IOException {
    44. ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
    45. SocketChannel clientChannel = serverChannel.accept();
    46. clientChannel.configureBlocking(false);
    47. clientChannel.register(selector, SelectionKey.OP_READ);
    48. System.out.println("New client connected: " + clientChannel.getRemoteAddress());
    49. }
    50. private void handleRead(SelectionKey key) throws IOException {
    51. SocketChannel clientChannel = (SocketChannel) key.channel();
    52. buffer.clear();
    53. int bytesRead = clientChannel.read(buffer);
    54. if (bytesRead == -1) {
    55. // 客户端关闭连接
    56. key.cancel();
    57. clientChannel.close();
    58. System.out.println("Client disconnected: " + clientChannel.getRemoteAddress());
    59. return;
    60. }
    61. buffer.flip();
    62. byte[] data = new byte[buffer.remaining()];
    63. buffer.get(data);
    64. System.out.println("Received message from client: " + new String(data));
    65. }
    66. public static void main(String[] args) {
    67. try {
    68. AsyncNonBlockingServer server = new AsyncNonBlockingServer(8080);
    69. server.start();
    70. } catch (IOException e) {
    71. e.printStackTrace();
    72. }
    73. }
    74. }

    多路复用器在java层面最核心的就是这一行了:selector.select();

    它在操作系统层面的实现,早期都是select,但是select支持的文件描述符(每一个连接都可以看做是一个文件描述)数量有限制,于是后来又出现了poll,相比于select,没有文件描述符的限制

    总结一:相比于传统的NIO模型,多路复用模型在询问操作系统数据准备好没有的时候,是一次性把所有的文件描述符传递给内核,也就是每一轮循环,只涉及到一次用户态和内核态的切换,而传统的NIO,因为遍历连接是在应用程序层面进行的,在询问每一个连接数据准备好与否的时候都会涉及到一次用户态和内核态的切换,所以多路复用模型要比传统的NIO模型性能更高

    不论是select还是poll都会涉及到文件描述符的遍历的过程,那么有没有一种办法消除这个遍历的过程呢,epoll的出现就解决了这个问题,下面讲解一下epoll的原理过程:

    1. 应用程序调用epoll_create,内核会在内存里面开辟一块内存空间,用于存放应用程序打开的文件描述附,数据结构采用的是红黑树
    2. 应用程序调用epoll_ctl将文件描述符添加到第一步创建的内存空间里面去
    3. 当文件描述符对应的socket数据准备好之后,内核会开辟另外一快空间(链表),将数据已经准备好的文件描述符拷贝到该空间中去,至于如何判断数据是否到达了,这个涉及到计算机组成原理里面的中断
    4. 应用程序调用epoll_wait询问操作系统数据准备好没有,内核直接返回第三步链表里面的文件描述符,应用程序拿着文件描述符去读取数据

    总结二:epoll相比于poll和select,减少了文件描述符的遍历过程,相当于是用空间换时间

    那么如何验证我们的程序在运行的时候到底使用的是poll还是epoll呢,这里同样也要通过strace命令来追踪系统调用:

    strace -ff -o ./strace_out/out java -cp test.jar org.example.netty.NettyServer

    通过这个命令来启动一个简单的netty程序,然后查看输出的系统调用详细过程,比如上面启动的netty程序就是采用的epoll了:

    ps:

    在Java中,如果你使用的是NIO库(例如Socket或ServerSocket),那么底层使用的可能是poll或epoll。但是,如果你使用的是AIO库(例如AsynchronousSocketChannel或AsynchronousServerSocketChannel),那么底层使用的肯定是epoll

  • 相关阅读:
    Linux中文乱码问题终极解决方法
    TorchServe搭建codeBERT分类模型服务
    深度学习入门(四十七)计算机视觉——SSD和YOLO简介
    书生·浦语大模型全链路开源体系-笔记&作业4
    动态内存管理
    Spring Boot 集成freemarker模板引擎
    Gitlab用户角色权限Guest、Reporter、Developer、Master、Owner
    《数据库系统概论》王珊版课后习题
    计算机组成原理习题课第三章-5(唐朔飞)
    Nacos版本升级
  • 原文地址:https://blog.csdn.net/qq_17805707/article/details/133267201