天天看点

JDK7新特性<八>异步io/AIO

概述

JDK7引入了Asynchronous I/O。I/O编程中,常用到两种模式:Reactor 和 Proactor。Reactor就是Java的NIO。当有事件触发时,我们得到通知,进行相应的处理。Proactor就是我们今天要讲的 AIO了。AIO进行I/O操作,都是异步处理,当事件完成时,我们会得到通知。

JDK7的 AIO包括网络和文件操作。两者大同小异,本文通过一个完整的客户端/服务器Sample来详细说明aio的网络操作。

AIO提供了两种异步操作的监听机制。第一种通过返回一个Future对象来事件,调用其get()会等到操作完成。第二种类似于回调函数。在进行异步操作时,传递一个CompletionHandler,当异步操作结束时,会调用CompletionHandler.complete 接口

范例

    这个范例功能比较简单,就是客户端向服务端发送一个“test”命令,然后结束。

      服务端程序 Sever.java

Java代码  

  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.nio.ByteBuffer;  
  4. import java.nio.channels.AsynchronousServerSocketChannel;  
  5. import java.nio.channels.AsynchronousSocketChannel;  
  6. import java.util.concurrent.ExecutionException;  
  7. import java.util.concurrent.Future;  
  8. import java.util.concurrent.TimeUnit;  
  9. import java.util.concurrent.TimeoutException;  
  10. public class Server {  
  11.     private AsynchronousServerSocketChannel server;  
  12.     public Server()throws IOException{  
  13.         server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8888));  
  14.     }  
  15.     public void start() throws InterruptedException, ExecutionException, TimeoutException{  
  16.         Future<AsynchronousSocketChannel> future = server.accept();  
  17.         AsynchronousSocketChannel socket = future.get();  
  18.         ByteBuffer readBuf = ByteBuffer.allocate(1024);  
  19.         socket.read(readBuf).get(100, TimeUnit.SECONDS);  
  20.         System.out.printf("Receiver:%s%n",new String(readBuf.array()));  
  21.     public static void main(String args[]) throws Exception{  
  22.         new Server().start();  
  23. }  

 客户端程序 (Future版本)

  1. public class AIOClientWithFuture {  
  2.     private final AsynchronousSocketChannel client;  
  3.     public AIOClientWithFuture() throws IOException{  
  4.         client = AsynchronousSocketChannel.open();  
  5.     public void sendMsg() throws InterruptedException, ExecutionException{  
  6.         client.connect(new InetSocketAddress("localhost",8888));  
  7.         client.write(ByteBuffer.wrap("test".getBytes())).get();  
  8.     public static void main(String...args) throws Exception{  
  9.         AIOClientWithFuture client = new AIOClientWithFuture();  
  10.         client.sendMsg();  

 客户端程序(CompleteHandler版本)

  1. import java.nio.channels.CompletionHandler;  
  2. public class AIOClientWithHandler {  
  3.     private final AsynchronousSocketChannel client ;  
  4.     public AIOClientWithHandler() throws Exception{  
  5.        client = AsynchronousSocketChannel.open();  
  6.     public void start()throws Exception{  
  7.         client.connect(new InetSocketAddress("127.0.0.1",8888),null,new CompletionHandler<Void,Void>() {  
  8.             @Override  
  9.             public void completed(Void result, Void attachment) {  
  10.                 try {  
  11.                     client.write(ByteBuffer.wrap("test".getBytes())).get();  
  12.                 } catch (Exception ex) {  
  13.                     ex.printStackTrace();  
  14.                 }  
  15.             }  
  16.             public void failed(Throwable exc, Void attachment) {  
  17.                 exc.printStackTrace();  
  18.         });  
  19.     public static void main(String args[])throws Exception{  
  20.         new AIOClientWithHandler().start();  

 相关类说明

AsynchronousSocketChannel 跟 SocketChannel操作类似,只不过改成异步接口了

AsynchronousServerSocketChannel跟ServerSocketChannel操作类似,只不过改成异步接口了

CompletionHandler 接口包括两个方法

    void completed(V result, A attachment);

    void failed(Throwable exc, A attachment);

总结

       本文只是对jdk7的aio使用做了一个简单的说明。至于其性能提升多少,如何改进现有的网络应用程序,还在摸索中。这里推荐一个比较成熟的网络框架Project Grizzly:​​http://grizzly.dev.java.net​​。据说已经用aio重新实现了,有兴趣的同学可以去研究一下源码。