gpt4 book ai didi

java - 非阻塞 IO 与异步 IO 以及 Java 中的实现

转载 作者:IT老高 更新时间:2023-10-28 13:53:57 28 4
gpt4 key购买 nike

试图为自己总结这两个概念之间的区别(因为当我看到人们在一个句子中同时使用这两个概念时,我真的很困惑,例如“非阻塞异步 IO”,我试图弄清楚它是什么意思)。

因此,在我的理解中,非阻塞 IO 是主要的操作系统机制来处理 IO,如果有任何数据准备好,否则就返回错误/什么都不做。

在异步 IO 中,您只需提供一个回调,当数据可用时,您的应用程序将收到通知。

那么究竟什么是“非阻塞异步 IO”?以及如何在 Java 中实现所有这些(标准 JDK,没有外部库,我知道有 java.nio.channels.{Channels, Selector, SelectorKey}java.nio.channels.{AsynchronousSocketChannel}):非阻塞 IO、异步 IO 和非阻塞异步 IO(如果有的话)?

最佳答案

So what is actually "non-blocking async IO"?



要回答这个问题,您必须首先了解没有阻塞异步 I/O 之类的东西。异步的概念表明没有等待,没有阻塞,没有延迟。当您看到非阻塞异步 I/O 时,非阻塞位仅用于进一步限定该术语中的异步形容词。如此有效地,非阻塞异步 I/O 可能有点冗余。

主要有两种I/O。 同步异步 . 同步阻塞当前执行线程直到处理完成 , 而 异步不会阻塞当前的执行线程,而是将控制权传递给操作系统内核以进行进一步处理。当提交的任务完成时,内核然后通知异步线程

异步 channel 组

java中异步 channel 的概念是由异步 channel 组支持的。异步 channel 组基本上汇集了许多 channel 以供重用。异步 api 的使用者从组中检索一个 channel (JVM 默认创建一个), channel 在完成读/写操作后自动将自己放回组中。最终,异步 channel 组得到了意外的线程池的支持。此外,异步 channel 是线程安全的。

支持异步 channel 组的线程池的大小由以下 JVM 属性配置
java.nio.channels.DefaultThreadPool.initialSize

其中,给定一个整数值将设置一个该大小的线程池,以支持 channel 组。否则, channel 组的创建和维护对开发人员是透明的。

And how all them can be implemented in Java



嗯,我很高兴你问。这是一个 AsynchronousSocketChannel 的例子(用于打开非阻塞客户端 Socket 到监听服务器。)此示例摘自 Apress Pro Java NIO.2 ,我的评论:
//Create an Asynchronous channel. No connection has actually been established yet
AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open();

/**Connect to an actual server on the given port and address.
The operation returns a type of Future, the basis of the all
asynchronous operations in java. In this case, a Void is
returned because nothing is returned after a successful socket connection
*/
Void connect = asynchronousSocketChannel.connect(new InetSocketAddress("127.0.0.1", 5000)).get();


//Allocate data structures to use to communicate over the wire
ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes());

//Send the message

Future<Integer> successfullyWritten= asynchronousSocketChannel.write(helloBuffer);

//Do some stuff here. The point here is that asynchronousSocketChannel.write()
//returns almost immediately, not waiting to actually finish writing
//the hello to the channel before returning control to the currently executing thread

doSomethingElse();

//now you can come back and check if it was all written (or not)

System.out.println("Bytes written "+successfullyWritten.get());

编辑:我应该提到对 Async NIO 的支持来自 JDK 1.7

关于java - 非阻塞 IO 与异步 IO 以及 Java 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25099640/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com