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.   
  11. public class Server {  
  12.     private AsynchronousServerSocketChannel server;  
  13.       
  14.     public Server()throws IOException{  
  15.         server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8888));  
  16.     }  
  17.       
  18.     public void start() throws InterruptedException, ExecutionException, TimeoutException{  
  19.         Future<AsynchronousSocketChannel> future = server.accept();  
  20.         AsynchronousSocketChannel socket = future.get();  
  21.          
  22.         ByteBuffer readBuf = ByteBuffer.allocate(1024);  
  23.         socket.read(readBuf).get(100, TimeUnit.SECONDS);  
  24.           
  25.         System.out.printf("Receiver:%s%n",new String(readBuf.array()));  
  26.     }  
  27.       
  28.     public static void main(String args[]) throws Exception{  
  29.         new Server().start();  
  30.     }  
  31. }  

 客户端程序 (Future版本)

Java代码  
  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.nio.ByteBuffer;  
  4. import java.nio.channels.AsynchronousSocketChannel;  
  5. import java.util.concurrent.ExecutionException;  
  6.   
  7. public class AIOClientWithFuture {  
  8.     private final AsynchronousSocketChannel client;  
  9.       
  10.     public AIOClientWithFuture() throws IOException{  
  11.         client = AsynchronousSocketChannel.open();  
  12.     }  
  13.       
  14.     public void sendMsg() throws InterruptedException, ExecutionException{  
  15.         client.connect(new InetSocketAddress("localhost",8888));  
  16.         client.write(ByteBuffer.wrap("test".getBytes())).get();  
  17.     }  
  18.     public static void main(String...args) throws Exception{  
  19.         AIOClientWithFuture client = new AIOClientWithFuture();  
  20.         client.sendMsg();  
  21.     }  
  22. }  

 客户端程序(CompleteHandler版本)

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

 相关类说明

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重新实现了,有兴趣的同学可以去研究一下源码。

参考资料

(以下有些资料使用的jdk7版本太低,很多接口已经更改了,慎入!:)

http://www.ibm.com/developerworks/java/library/j-nio2-1/index.html?

http://www.iteye.com/topic/446298

http://www.iteye.com/topic/472333

本文是jdk7系列的终结了,感谢大家的支持!更多的内容可以访问我的blog

http://www.iamcoding.com

原文地址:https://www.cnblogs.com/zhwl/p/4732751.html