天天看點

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重新實作了,有興趣的同學可以去研究一下源碼。