小Q:什么是 AIO 呢?
AIO 即 Asynchronous I/O,异步非阻塞 I/O 模型。
小Q:AIO 和 NIO 的区别是什么呢?
慢慢:我们知道 NIO 是同步非阻塞模型,其不管是普通 NIO 还是多路复用,都需要去轮询查看有没有事件发生,而这个不断的轮询也是对应者同步的概念。
AIO 则没有了轮询的过程。通过对事件绑定一个回调函数,当事件发生时就会自动触发这个回调函数。当然,这得需要硬件的强力支持。
小Q:有没有代码演示下。
慢慢:那我们来模拟下读取磁盘操作。
@Slf4j
public class AioFileChannel {
public static void main(String[] args) {
AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt") StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(16);
lob.debug("read begin...");
// 参数1 bytebuffer;参数2 读取的起始位置;参数3 附件;参数4 回调对象
channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
// read 成功
@Ovverride
public void completed(Integer result, ByteBuffer attachment) {
log.debug("read completed...");
attachment.flip();
}
// read 失败
public void failed(Throwable exc, ByteBuffer attachment) {
log.debug("read fail...");
}
});
log.debug("read end...");
} catch (Exception e) {
e.printStackTrace();
}
}