(aio)NIO 2.0引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。异步的套接字通道时真正的异步非阻塞I/O,对应于UNIX网络编程中的事件驱动I/O(AIO)。他不需要过多的Selector对注册的通道进行轮询即可实现异步读写,从而简化了NIO的编程模型。
jdk7以前的nio是非阻塞IO,操作系统底层比方说linux,是用IO复用select或者epoll实现的,也不是异步IO啊。异步IO在linux上目前仅限于文件系统,并且还没有得到广泛应用,很多平台都没有这玩意。
java aio在windows上是利用iocp实现的,这是真正的异步IO。而在linux上,是通过epoll模拟异步的。
AIO使用
AIO 提供四种类型的异步通道以及不同的 I/O 操作:
AsynchronousSocketChannel:connect,read,write
AsynchronousFileChannel:lock,read,write
AsynchronousServerSocketChannel:accept
AsynchronousDatagramChannel:read,write,send,receive
当然我们重点还是将网络IO(tcp)方面的使用,先关注 AsynchronousSocketChannel ,首先简单浏览一下该类型的 API。
AsynchronousSocketChannel类定义
public abstract class AsynchronousSocketChannel implements AsynchronousByteChannel, NetworkChannel
创建一个异步网络通道,并且绑定到一个默认组。
public static AsynchronousSocketChannel open() throws IOException
接着我们可以调用AsynchronousSocketChannel 的各种方法进行异步操作,调用时候需要传入一个CompletionHandler接口参数作为回调接口。
1.将异步网络通道连接到远程服务器,使用指定的 CompletionHandler 听候完成通知。
public abstract <A> void connect(SocketAddress remote, A attachment, CompletionHandler<Void,? super A> handler)
2.从异步网络通道读取数据到指定的缓冲区,使用指定的 CompletionHandler 听候完成通知。
public final <A> void read(ByteBuffer dst, A attachment, CompletionHandler<Integer,? super A> handler)
3.向异步网络通道写缓冲区中的数据,使用指定的 CompletionHandler 听候完成通知。
public final <A> void write(ByteBuffer src, A attachment, CompletionHandler<Integer,? super A> handler)
CompletionHandler接口,作为异步执行之后的处理接口,正确完成时回调completed(V result, A attachment)方法,执行失败回调void failed(Throwable exc, A attachment)方法。
public