当前位置: 首页 > news >正文

【java】BIO,NIO,多路IO复用,AIO

在Java中,处理I/O操作的模型主要有四种:阻塞I/O (BIO), 非阻塞I/O (NIO), 异步I/O (AIO), 以及IO多路复用。下面详细介绍这四种I/O模型的工作原理和应用场景。

1. 阻塞I/O (BIO)

工作原理

阻塞I/O是最传统的I/O模型。在这种模型中,当一个线程发起一个I/O请求(如读写操作)时,该线程会被阻塞,直到I/O操作完成。这意味着线程必须等待I/O操作完成才能继续执行。

代码示例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;public class BioServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(8080);System.out.println("Server started on port 8080");while (true) {Socket clientSocket = serverSocket.accept(); // 阻塞等待客户端连接new Thread(() -> {try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {String line;while ((line = reader.readLine()) != null) {System.out.println("Received: " + line);}} catch (IOException e) {e.printStackTrace();}}).start();}}
}
优点
  • 实现简单。
缺点
  • 每个连接都需要一个线程来处理,当并发连接数增加时,线程的数量也会增加,可能导致系统资源耗尽。

2. 非阻塞I/O (NIO)

工作原理

非阻塞I/O模型允许线程在发起I/O请求时不会被阻塞,如果数据不可用或设备忙,则立即返回一个错误或特殊值。线程可以选择立即再次尝试I/O操作或去做其他事情,从而提高了CPU的利用率。

代码示例
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;public class NioServer {public static void main(String[] args) throws IOException {Selector selector = Selector.open();ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.socket().bind(new InetSocketAddress(8080));serverSocketChannel.configureBlocking(false);serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {selector.select();Set<SelectionKey> selectedKeys = selector.selectedKeys();Iterator<SelectionKey> keyIterator = selectedKeys.iterator();while (keyIterator.hasNext()) {SelectionKey key = keyIterator.next();if (key.isAcceptable()) {ServerSocketChannel ssc = (ServerSocketChannel) key.channel();SocketChannel sc = ssc.accept();sc.configureBlocking(false);sc.register(selector, SelectionKey.OP_READ);} else if (key.isReadable()) {SocketChannel sc = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);int readBytes = sc.read(buffer);if (readBytes > 0) {buffer.flip();byte[] data = new byte[buffer.remaining()];buffer.get(data);System.out.println("Received: " + new String(data));}}keyIterator.remove();}}}
}
优点
  • 提高了单个线程处理多个连接的能力,降低了系统资源消耗。
  • 可以处理大量并发连接。
缺点
  • 实现相对复杂。
  • 需要手动管理缓冲区、选择器等。

3. IO多路复用

工作原理

IO多路复用允许一个进程同时监听多个文件描述符(例如socket),并只在某个描述符准备好进行读写操作时才进行处理。常用的多路复用机制有selectpollepoll。这种模型非常适合处理大量并发连接的场景。

代码示例
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;public class SelectServer {public static void main(String[] args) throws IOException {Selector selector = Selector.open();ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.socket().bind(new InetSocketAddress(8080));serverSocketChannel.configureBlocking(false);serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {selector.select();for (SelectionKey key : selector.selectedKeys()) {if (key.isAcceptable()) {ServerSocketChannel ssc = (ServerSocketChannel) key.channel();SocketChannel sc = ssc.accept();sc.configureBlocking(false);sc.register(selector, SelectionKey.OP_READ);} else if (key.isReadable()) {SocketChannel sc = (SocketChannel) key.channel();// 读取数据...}}selector.selectedKeys().clear();}}
}
优点
  • 可以同时监听多个文件描述符,提高处理大量并发连接的能力。
  • 提高了资源利用率。
缺点
  • 在Java中,selectpoll的性能不如epoll,后者仅在Linux系统中可用。

4. 异步I/O (AIO)

工作原理

异步I/O是真正的异步操作模型,进程发起I/O请求后可以立即返回并继续执行其他任务,而无需等待I/O操作完成。当I/O操作完成后,操作系统会通知进程结果。

代码示例
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;public class AioServer {private static final CountDownLatch latch = new CountDownLatch(1);public static void main(String[] args) throws IOException, InterruptedException {AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(new java.net.InetSocketAddress(8080));server.accept(null, new AcceptHandler(server));latch.await();}static class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Object> {private AsynchronousServerSocketChannel server;public AcceptHandler(AsynchronousServerSocketChannel server) {this.server = server;}@Overridepublic void completed(AsynchronousSocketChannel result, Object attachment) {result.read(ByteBuffer.allocate(1024), null, new ReadHandler(result));server.accept(null, this);}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();latch.countDown();}}static class ReadHandler implements CompletionHandler<Integer, Object> {private AsynchronousSocketChannel channel;public ReadHandler(AsynchronousSocketChannel channel) {this.channel = channel;}@Overridepublic void completed(Integer result, Object attachment) {ByteBuffer buffer = (ByteBuffer) attachment;buffer.flip();byte[] data = new byte[buffer.remaining()];buffer.get(data);System.out.println("Received: " + new String(data));channel.close();}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();try {((AsynchronousSocketChannel) attachment).close();} catch (IOException e) {e.printStackTrace();}}}
}
优点
  • 真正的异步操作,提高了系统的并发能力和响应速度。
  • 适用于高并发场景。
缺点
  • 实现较为复杂。
  • Java中AIO的支持相对较少,不如NIO成熟。

总结

  • BIO:适合连接数较少的场景。
  • NIO:适用于中等并发的场景,提高了资源利用率。
  • IO多路复用:适合大量并发连接的场景,特别是在服务器端。
  • AIO:适用于高并发场景,真正实现了异步操作。

选择哪种模型取决于具体的应用场景和需求。例如,对于需要处理大量并发连接的服务器,IO多路复用和异步I/O可能是更佳的选择。而对于简单的、单线程的应用,阻塞I/O可能就已经足够。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 强化学习笔记
  • 视觉机械臂抓取——流程总览
  • 如何在测试中保护用户隐私!
  • Golang | Leetcode Golang题解之第300题最长递增子序列
  • Github2024-07-29 开源项目周报Top15
  • easyui 点击单元格的时候,获取该行另外一个字段的值
  • CVPR 2024 最佳论文分享┆物体用体积表示:一种不透明固体图形的随机几何表示方法
  • C++拷贝和移动
  • 视频剪辑常用工具
  • C# 字符串罗马数字123转汉字一二三
  • Java中的异常总结
  • InternLM Git 基础知识
  • SAPUI5基础知识20 - 对话框和碎片(Dialogs and Fragments)
  • 需要消化的知识点
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • “Material Design”设计规范在 ComponentOne For WinForm 的全新尝试!
  • 【技术性】Search知识
  • C++入门教程(10):for 语句
  • css属性的继承、初识值、计算值、当前值、应用值
  • ES2017异步函数现已正式可用
  • Essential Studio for ASP.NET Web Forms 2017 v2,新增自定义树形网格工具栏
  • Git的一些常用操作
  • Java|序列化异常StreamCorruptedException的解决方法
  • JavaScript/HTML5图表开发工具JavaScript Charts v3.19.6发布【附下载】
  • leetcode讲解--894. All Possible Full Binary Trees
  • Python连接Oracle
  • React-Native - 收藏集 - 掘金
  • Redis 懒删除(lazy free)简史
  • Redux系列x:源码分析
  • SpiderData 2019年2月25日 DApp数据排行榜
  • Zepto.js源码学习之二
  • 服务器之间,相同帐号,实现免密钥登录
  • 关于List、List?、ListObject的区别
  • 回顾 Swift 多平台移植进度 #2
  • 将 Measurements 和 Units 应用到物理学
  • 使用putty远程连接linux
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 网络应用优化——时延与带宽
  • 线上 python http server profile 实践
  • 小程序开发中的那些坑
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 小而合理的前端理论:rscss和rsjs
  • 写代码的正确姿势
  • 移动端解决方案学习记录
  • 优化 Vue 项目编译文件大小
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • 运行时添加log4j2的appender
  • ​ 无限可能性的探索:Amazon Lightsail轻量应用服务器引领数字化时代创新发展
  • # 深度解析 Socket 与 WebSocket:原理、区别与应用
  • #APPINVENTOR学习记录
  • #git 撤消对文件的更改
  • #LLM入门|Prompt#2.3_对查询任务进行分类|意图分析_Classification
  • #数据结构 笔记一
  • $$$$GB2312-80区位编码表$$$$