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

BIO,NIO,AIO

BIO、NIO 和 AIO 是三种不同的 I/O 模型,它们分别代表了不同的 I/O 处理方式。

  • BIO (Blocking I/O) - 阻塞 I/O

  • NIO (Non-blocking I/O) - 非阻塞 I/O

  • AIO (Asynchronous I/O) - 异步 I/O

BIO(Blocking I/O)

BIO 模型是 Java 最传统的 I/O 模型,基于流的同步阻塞 I/O 操作。每个连接都会占用一个线程,当进行 I/O 操作时,线程会被阻塞,直到操作完成。适用于连接数较少且固定的架构,例如传统的 C/S 架构,因其实现简单、编程直观。

特点:

  • 同步阻塞:每个 I/O 操作都会阻塞当前线程,直到操作完成。

  • 线程占用:每个连接需要一个独立的线程,线程资源消耗较大。

  • 实现简单:代码实现相对简单,易于理解和编写。

import java.io.*;
import java.net.*;public class BIOServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(8080);while (true) {Socket socket = serverSocket.accept();new Thread(() -> {try {BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);String message;while ((message = reader.readLine()) != null) {writer.println(message);}} catch (IOException e) {e.printStackTrace();}}).start();}}
}
NIO(Non-blocking I/O)

NIO 是 Java 1.4 引入的新 I/O API,基于通道(Channel)和缓冲区(Buffer)的非阻塞 I/O 操作。它支持非阻塞模式,允许一个线程管理多个连接,实现了多路复用(Selector)。适用于连接数较多且连接较短的架构,如高并发的服务器端应用。

特点:

  • 非阻塞:I/O 操作不会阻塞线程,线程可以在等待数据时执行其他任务。

  • 多路复用:通过 Selector 可以管理多个 Channel,提高了资源利用率。

  • 高性能:适用于高并发场景,减少线程开销和上下文切换。

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;public class NIOServer {public static void main(String[] args) throws IOException {Selector selector = Selector.open();ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.bind(new InetSocketAddress(8080));serverSocketChannel.configureBlocking(false);serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {selector.select();Iterator<SelectionKey> keys = selector.selectedKeys().iterator();while (keys.hasNext()) {SelectionKey key = keys.next();keys.remove();if (key.isAcceptable()) {ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();SocketChannel socketChannel = serverChannel.accept();socketChannel.configureBlocking(false);socketChannel.register(selector, SelectionKey.OP_READ);} else if (key.isReadable()) {SocketChannel socketChannel = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);int bytesRead = socketChannel.read(buffer);if (bytesRead > 0) {buffer.flip();socketChannel.write(buffer);} else if (bytesRead == -1) {socketChannel.close();}}}}}
}

 

AIO(Asynchronous I/O)

AIO 是 Java 7 引入的异步 I/O API,基于异步通道(AsynchronousChannel)和异步回调机制。AIO 操作是非阻塞和异步的,即操作立即返回,结果通过回调函数处理。适用于连接数较多且连接时间较长的架构,如高并发的服务器端应用。

特点:

  • 异步非阻塞:I/O 操作是异步的,通过回调处理结果,不阻塞线程。

  • 回调机制:通过回调函数处理 I/O 操作结果,提高了程序的灵活性。

  1. 发起异步 I/O 操作:程序发起一个异步 I/O 请求,并提供一个回调函数。

  2. 继续执行其他任务:程序无需等待 I/O 操作完成,而是立即返回,继续执行其他任务。

  3. I/O 操作完成:当 I/O 操作完成后,系统会调用之前提供的回调函数,传递结果或状态信息。

  4. 处理结果:回调函数负责处理 I/O 操作的结果,如读取数据或处理错误。

  • 高性能:适用于高并发、高吞吐量的场景。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;public class AIOServer {public static void main(String[] args) throws IOException {AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();serverChannel.bind(new InetSocketAddress(8080));serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {@Overridepublic void completed(AsynchronousSocketChannel result, Void attachment) {serverChannel.accept(null, this);ByteBuffer buffer = ByteBuffer.allocate(1024);result.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {@Overridepublic void completed(Integer bytesRead, ByteBuffer buffer) {if (bytesRead > 0) {buffer.flip();result.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {@Overridepublic void completed(Integer result, ByteBuffer attachment) {buffer.clear();result.read(buffer, buffer, this);}@Overridepublic void failed(Throwable exc, ByteBuffer attachment) {try {result.close();} catch (IOException e) {e.printStackTrace();}}});}}@Overridepublic void failed(Throwable exc, ByteBuffer attachment) {try {result.close();} catch (IOException e) {e.printStackTrace();}}});}@Overridepublic void failed(Throwable exc, Void attachment) {System.err.println("Failed to accept connection: " + exc);}});// Prevent the main thread from exitingwhile (true) {// The server continues to run, accepting connections}}
}
总结
  • BIO 适用于连接数较少且固定的情况,编程简单直观,但每个连接需要一个线程,线程资源消耗大。

  • NIO 适用于高并发的场景,通过多路复用机制(Selector)管理多个连接,提高资源利用率和性能。

  • AIO 适用于高并发、高吞吐量的场景,通过异步非阻塞 I/O 和回调机制进一步提高性能和灵活性。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【图解IO与Netty系列】Netty核心组件解析
  • 地图元素。
  • MySQL快速入门(极简)
  • Buildroot和Debian文件系统修改方法
  • Java的IO流
  • VBA即用型代码手册:删除重复行Delete Duplicate Rows
  • 七天进阶elasticsearch[two]
  • 暴雨推出X705显示器:23.8英寸100Hz IPS屏
  • 重写setter方法要小心递归调用
  • [word] word悬挂缩进怎么设置? #经验分享#职场发展#经验分享
  • 25.逢七必过
  • Docker 学习总结(83)—— 配置文件daemon.json介绍及优化建议
  • python学习 - 在线 百度语音API 播报 测试案例分析
  • 二叉树最大宽度
  • 论文略读:Onthe Expressivity Role of LayerNorm in Transformers’ Attention
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • Hibernate【inverse和cascade属性】知识要点
  • JAVA SE 6 GC调优笔记
  • JAVA 学习IO流
  • Joomla 2.x, 3.x useful code cheatsheet
  • Js基础——数据类型之Null和Undefined
  • JS题目及答案整理
  • mysql 数据库四种事务隔离级别
  • mysql_config not found
  • React的组件模式
  • seaborn 安装成功 + ImportError: DLL load failed: 找不到指定的模块 问题解决
  • TypeScript迭代器
  • 包装类对象
  • 大型网站性能监测、分析与优化常见问题QA
  • 扑朔迷离的属性和特性【彻底弄清】
  • 实战:基于Spring Boot快速开发RESTful风格API接口
  • 线上 python http server profile 实践
  • Java数据解析之JSON
  • 京东物流联手山西图灵打造智能供应链,让阅读更有趣 ...
  • 小白应该如何快速入门阿里云服务器,新手使用ECS的方法 ...
  • ​​​​​​​​​​​​​​汽车网络信息安全分析方法论
  • ‌分布式计算技术与复杂算法优化:‌现代数据处理的基石
  • #HarmonyOS:软件安装window和mac预览Hello World
  • #进阶:轻量级ORM框架Dapper的使用教程与原理详解
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (BAT向)Java岗常问高频面试汇总:MyBatis 微服务 Spring 分布式 MySQL等(1)
  • (CPU/GPU)粒子继承贴图颜色发射
  • (笔记)Kotlin——Android封装ViewBinding之二 优化
  • (区间dp) (经典例题) 石子合并
  • (删)Java线程同步实现一:synchronzied和wait()/notify()
  • (译)2019年前端性能优化清单 — 下篇
  • (源码分析)springsecurity认证授权
  • (转)AS3正则:元子符,元序列,标志,数量表达符
  • (转)memcache、redis缓存
  • ... fatal error LINK1120:1个无法解析的外部命令 的解决办法
  • .NET 中使用 TaskCompletionSource 作为线程同步互斥或异步操作的事件
  • @RequestMapping 和 @GetMapping等子注解的区别及其用法
  • [ vulhub漏洞复现篇 ] AppWeb认证绕过漏洞(CVE-2018-8715)