jdk7 AIO 入門

隨着JDK7的發佈,Java的AIO正式支持版本也出爐了,就像當年發佈NIO特性支持時,基本上所有的Java服務器都重寫了自己的網絡框架以通過NIO來提高服務器的性能。AIO的發佈勢必也會引起Java界的一次重寫風潮,現在很多的網絡框架(如Mina),大型軟件(如Oracle DB)都宣佈自己已經在新版本中支持了AIO的特性以提高性能。下面就來看一下aio的基本原理,以及如何使用JDK7的AIO特性。
    所謂AIO,異步IO,其主要是針對進程在調用IO獲取外部數據時,是否阻塞調用進程而言的。一個進程的IO調用步驟大致如下:
    1、進程向操作系統請求數據
    2、操作系統把外部數據加載到內核的緩衝區中,
    3、操作系統把內核的緩衝區拷貝到進程的緩衝區
    4、進程獲得數據完成自己的功能
   
    當操作系統在把外部數據放到進程緩衝區的這段時間(即上述的第二,三步),如果應用進程是掛起等待的,那麼就是同步IO,反之,就是異步IO,也就是AIO
    
    JDK對於IO支持基本上都是基於操作系統的封裝,而IO操作的核心就是如何有效的管理Channel(數據通道),JDK7對AIO的支持主要提供如下的一些封裝類:
AsynchronousChannel:所有AIO Channel的父類。
AsynchronousByteChannel:支持Byte讀寫的Channel
AsynchronousDatagramChannel:支持數據包(datagram)讀寫的Channel
AsynchronousFileChannel:支持文件讀寫的Channel
AsynchronousServerSocketChannel:支持數據流讀寫的服務器端Channel
AsynchronousSocketChannel:支持數據流讀寫的客戶端Channel
AsynchronousChannelGroup:支持資源共享的Channel分組

   對於AIO的Channel,JDK定義了2種類型的操作,
1、Future operation(....):即 通過Future判斷是操作是否完成。
2、void operation(Object attachment, CompletionHandler handler):即通過CompletionHandler來通知異步IO完成。

下面就是一個AsynchronousFileChannel實現的完整異步讀寫文件的例子
Java代碼 複製代碼 收藏代碼
  1. package com.jdk7.io.aio;  
  2.   
  3.   
  4. import java.io.IOException;  
  5. import java.nio.ByteBuffer;  
  6. import java.nio.channels.AsynchronousFileChannel;  
  7. import java.nio.channels.CompletionHandler;  
  8. import java.nio.file.Path;  
  9. import java.nio.file.Paths;  
  10. import java.util.concurrent.ExecutionException;  
  11. import java.util.concurrent.Future;  
  12.   
  13. /** 
  14.  * Created with IntelliJ IDEA. 
  15.  * User: twer 
  16.  * Date: 5/2/12 
  17.  * Time: 8:37 PM 
  18.  * To change this template use File | Settings | File Templates. 
  19.  */  
  20. public class AFCDemo {  
  21.     static Thread current;  
  22.   
  23.     public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {  
  24.         if (args == null || args.length == 0) {  
  25.             System.out.println("Please input file path");  
  26.             return;  
  27.         }  
  28.         Path filePath = Paths.get(args[0]);  
  29.         AsynchronousFileChannel afc = AsynchronousFileChannel.open(filePath);  
  30.         ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 1024);  
  31. //使用FutureDemo時,請註釋掉completionHandlerDemo,反之亦然  
  32.         futureDemo(afc, byteBuffer);  
  33.         completionHandlerDemo(afc, byteBuffer);  
  34.     }  
  35.   
  36.     private static void completionHandlerDemo(AsynchronousFileChannel afc, ByteBuffer byteBuffer) throws IOException {  
  37.         current = Thread.currentThread();  
  38.         afc.read(byteBuffer, 0nullnew CompletionHandler<Integer, Object>() {  
  39.             @Override  
  40.             public void completed(Integer result, Object attachment) {  
  41.                 System.out.println("Bytes Read = " + result);  
  42.                 current.interrupt();  
  43.             }  
  44.   
  45.             @Override  
  46.             public void failed(Throwable exc, Object attachment) {  
  47.                 System.out.println(exc.getCause());  
  48.                 current.interrupt();  
  49.             }  
  50.         });  
  51.         System.out.println("Waiting for completion...");  
  52.         try {  
  53.             current.join();  
  54.         } catch (InterruptedException e) {  
  55.         }  
  56.         System.out.println("End");  
  57.         afc.close();  
  58.     }  
  59.   
  60.     private static void futureDemo(AsynchronousFileChannel afc, ByteBuffer byteBuffer) throws InterruptedException, ExecutionException, IOException {  
  61.         Future<Integer> result = afc.read(byteBuffer, 0);  
  62.         while (!result.isDone()) {  
  63.             System.out.println("Waiting file channel finished....");  
  64.             Thread.sleep(1);  
  65.         }  
  66.         System.out.println("Finished? = " + result.isDone());  
  67.         System.out.println("byteBuffer = " + result.get());  
  68.         System.out.println(byteBuffer);  
  69.         afc.close();  
  70.     }  
  71. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章