Nio2.0

Java nio 2.0的主要改進就是引入了異步IO(包括文件和網絡),這裏主要介紹下異步網絡IO API的使用以及框架的設計,以TCP服務端爲例。首先看下爲了支持AIO引入的新的類和接口:

 java.nio.channels.AsynchronousChannel
       標記一個channel支持異步IO操作。

 java.nio.channels.AsynchronousServerSocketChannel
       ServerSocket的aio版本,創建TCP服務端,綁定地址,監聽端口等。

 java.nio.channels.AsynchronousSocketChannel
       面向流的異步socket channel,表示一個連接。

 java.nio.channels.AsynchronousChannelGroup
       異步channel的分組管理,目的是爲了資源共享。一個AsynchronousChannelGroup綁定一個線程池,這個線程池執行兩個任務:處理IO事件和派發CompletionHandler。AsynchronousServerSocketChannel創建的時候可以傳入一個 AsynchronousChannelGroup,那麼通過AsynchronousServerSocketChannel創建的 AsynchronousSocketChannel將同屬於一個組,共享資源。

 java.nio.channels.CompletionHandler
       異步IO操作結果的回調接口,用於定義在IO操作完成後所作的回調工作。AIO的API允許兩種方式來處理異步操作的結果:返回的Future模式或者註冊CompletionHandler,我更推薦用CompletionHandler的方式,這些handler的調用是由 AsynchronousChannelGroup的線程池派發的。顯然,線程池的大小是性能的關鍵因素。AsynchronousChannelGroup允許綁定不同的線程池,通過三個靜態方法來創建:

Java代碼 複製代碼 收藏代碼

  1. public static AsynchronousChannelGroup withFixedThreadPool(int nThreads,   

  2.                                                               ThreadFactory threadFactory)   

  3.        throws IOException   

  4.   

  5. public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor,   

  6.                                                                int initialSize)   

  7.   

  8. public static AsynchronousChannelGroup withThreadPool(ExecutorService executor)   

  9.        throws IOException  

Java代碼  收藏代碼

  1. public static AsynchronousChannelGroup withFixedThreadPool(int nThreads,  

  2.                                                               ThreadFactory threadFactory)  

  3.        throws IOException  

  4.   

  5. public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor,  

  6.                                                                int initialSize)  

  7.   

  8. public static AsynchronousChannelGroup withThreadPool(ExecutorService executor)  

  9.        throws IOException  

 

     需要根據具體應用相應調整,從框架角度出發,需要暴露這樣的配置選項給用戶。

     在介紹完了aio引入的TCP的主要接口和類之後,我們來設想下一個aio框架應該怎麼設計。參考非阻塞nio框架的設計,一般都是採用Reactor模式,Reacot負責事件的註冊、select、事件的派發;相應地,異步IO有個Proactor模式,Proactor負責 CompletionHandler的派發,查看一個典型的IO寫操作的流程來看兩者的區別:

     Reactor:  send(msg) -> 消息隊列是否爲空,如果爲空  -> 向Reactor註冊OP_WRITE,然後返回 -> Reactor select -> 觸發Writable,通知用戶線程去處理 ->先註銷Writable(很多人遇到的cpu 100%的問題就在於沒有註銷),處理Writeable,如果沒有完全寫入,繼續註冊OP_WRITE。注意到,寫入的工作還是用戶線程在處理。
     Proactor: send(msg) -> 消息隊列是否爲空,如果爲空,發起read異步調用,並註冊CompletionHandler,然後返回。 -> 操作系統負責將你的消息寫入,並返回結果(寫入的字節數)給Proactor -> Proactor派發CompletionHandler。可見,寫入的工作是操作系統在處理,無需用戶線程參與。事實上在aio的API 中,AsynchronousChannelGroup就扮演了Proactor的角色

    CompletionHandler有三個方法,分別對應於處理成功、失敗、被取消(通過返回的Future)情況下的回調處理:

Java代碼 複製代碼 收藏代碼

  1. public interface CompletionHandler<V,A> {   

  2.   

  3.      void completed(V result, A attachment);   

  4.   

  5.     void failed(Throwable exc, A attachment);   

  6.   

  7.       

  8.     void cancelled(A attachment);   

  9. }  

Java代碼  收藏代碼

  1. public interface CompletionHandler<V,A> {  

  2.   

  3.      void completed(V result, A attachment);  

  4.   

  5.     void failed(Throwable exc, A attachment);  

  6.   

  7.      

  8.     void cancelled(A attachment);  

  9. }  

 


    其中的泛型參數V表示IO調用的結果,而A是發起調用時傳入的attchment。

    在初步介紹完aio引入的類和接口後,我們看看一個典型的tcp服務端是怎麼啓動的,怎麼接受連接並處理讀和寫,這裏引用的代碼都是yanf4j 的aio分支中的代碼,可以從svn checkout,svn地址:http://yanf4j.googlecode.com/svn/branches/yanf4j-aio

    第一步,創建一個AsynchronousServerSocketChannel,創建之前先創建一個 AsynchronousChannelGroup,上文提到AsynchronousServerSocketChannel可以綁定一個 AsynchronousChannelGroup,那麼通過這個AsynchronousServerSocketChannel建立的連接都將同屬於一個AsynchronousChannelGroup並共享資源:

Java代碼 複製代碼 收藏代碼

  1. this.asynchronousChannelGroup = AsynchronousChannelGroup   

  2.                     .withCachedThreadPool(Executors.newCachedThreadPool(),   

  3.                             this.threadPoolSize);  

Java代碼  收藏代碼

  1. this.asynchronousChannelGroup = AsynchronousChannelGroup  

  2.                     .withCachedThreadPool(Executors.newCachedThreadPool(),  

  3.                             this.threadPoolSize);  

     然後初始化一個AsynchronousServerSocketChannel,通過open方法:

Java代碼 複製代碼 收藏代碼

  1. this.serverSocketChannel = AsynchronousServerSocketChannel   

  2.                 .open(this.asynchronousChannelGroup);  

Java代碼  收藏代碼

  1. this.serverSocketChannel = AsynchronousServerSocketChannel  

  2.                 .open(this.asynchronousChannelGroup);  

 

    通過nio 2.0引入的SocketOption類設置一些TCP選項:

Java代碼 複製代碼 收藏代碼

  1. this.serverSocketChannel   

  2.                     .setOption(   

  3.                             StandardSocketOption.SO_REUSEADDR,true);   

  4. this.serverSocketChannel   

  5.                     .setOption(   

  6.                             StandardSocketOption.SO_RCVBUF,16*1024);  

Java代碼  收藏代碼

  1. this.serverSocketChannel  

  2.                     .setOption(  

  3.                             StandardSocketOption.SO_REUSEADDR,true);  

  4. this.serverSocketChannel  

  5.                     .setOption(  

  6.                             StandardSocketOption.SO_RCVBUF,16*1024);  

 


    綁定本地地址:

Java代碼 複製代碼 收藏代碼

  1. this.serverSocketChannel   

  2.                     .bind(new InetSocketAddress("localhost",8080), 100);  

Java代碼  收藏代碼

  1. this.serverSocketChannel  

  2.                     .bind(new InetSocketAddress("localhost",8080), 100);  

 

   
    其中的100用於指定等待連接的隊列大小(backlog)。完了嗎?還沒有,最重要的監聽工作還沒開始,監聽端口是爲了等待連接上來以便accept產生一個AsynchronousSocketChannel來表示一個新建立的連接,因此需要發起一個accept調用,調用是異步的,操作系統將在連接建立後,將最後的結果——AsynchronousSocketChannel返回給你:

Java代碼 複製代碼 收藏代碼

  1. public void pendingAccept() {   

  2.         if (this.started && this.serverSocketChannel.isOpen()) {   

  3.             this.acceptFuture = this.serverSocketChannel.accept(null,   

  4.                     new AcceptCompletionHandler());   

  5.   

  6.         } else {   

  7.             throw new IllegalStateException("Controller has been closed");   

  8.         }   

  9.     }  

Java代碼  收藏代碼

  1. public void pendingAccept() {  

  2.         if (this.started && this.serverSocketChannel.isOpen()) {  

  3.             this.acceptFuture = this.serverSocketChannel.accept(null,  

  4.                     new AcceptCompletionHandler());  

  5.   

  6.         } else {  

  7.             throw new IllegalStateException("Controller has been closed");  

  8.         }  

  9.     }  

 


   注意,重複的accept調用將會拋出PendingAcceptException,後文提到的read和write也是如此。accept方法的第一個參數是你想傳給CompletionHandler的attchment,第二個參數就是註冊的用於回調的CompletionHandler,最後返回結果Future<AsynchronousSocketChannel>。你可以對future做處理,這裏採用更推薦的方式就是註冊一個CompletionHandler。那麼accept的CompletionHandler中做些什麼工作呢?顯然一個赤裸裸的 AsynchronousSocketChannel是不夠的,我們需要將它封裝成session,一個session表示一個連接(mina裏就叫 IoSession了),裏面帶了一個緩衝的消息隊列以及一些其他資源等。在連接建立後,除非你的服務器只准備接受一個連接,不然你需要在後面繼續調用pendingAccept來發起另一個accept請求

Java代碼 複製代碼 收藏代碼

  1. private final class AcceptCompletionHandler implements  

  2.             CompletionHandler<AsynchronousSocketChannel, Object> {   

  3.   

  4.         @Override  

  5.         public void cancelled(Object attachment) {   

  6.             logger.warn("Accept operation was canceled");   

  7.         }   

  8.   

  9.         @Override  

  10.         public void completed(AsynchronousSocketChannel socketChannel,   

  11.                 Object attachment) {   

  12.             try {   

  13.                 logger.debug("Accept connection from "  

  14.                         + socketChannel.getRemoteAddress());   

  15.                 configureChannel(socketChannel);   

  16.                 AioSessionConfig sessionConfig = buildSessionConfig(socketChannel);   

  17.                 Session session = new AioTCPSession(sessionConfig,   

  18.                         AioTCPController.this.configuration   

  19.                                 .getSessionReadBufferSize(),   

  20.                         AioTCPController.this.sessionTimeout);   

  21.                 session.start();   

  22.                 registerSession(session);   

  23.             } catch (Exception e) {   

  24.                 e.printStackTrace();   

  25.                 logger.error("Accept error", e);   

  26.                 notifyException(e);   

  27.             } finally {   

  28.                 <STRONG>pendingAccept</STRONG>();   

  29.             }   

  30.         }   

  31.   

  32.         @Override  

  33.         public void failed(Throwable exc, Object attachment) {   

  34.             logger.error("Accept error", exc);   

  35.             try {   

  36.                 notifyException(exc);   

  37.             } finally {   

  38.                 <STRONG>pendingAccept</STRONG>();   

  39.             }   

  40.         }   

  41.     }  

Java代碼  收藏代碼

  1. private final class AcceptCompletionHandler implements  

  2.             CompletionHandler<AsynchronousSocketChannel, Object> {  

  3.   

  4.         @Override  

  5.         public void cancelled(Object attachment) {  

  6.             logger.warn("Accept operation was canceled");  

  7.         }  

  8.   

  9.         @Override  

  10.         public void completed(AsynchronousSocketChannel socketChannel,  

  11.                 Object attachment) {  

  12.             try {  

  13.                 logger.debug("Accept connection from "  

  14.                         + socketChannel.getRemoteAddress());  

  15.                 configureChannel(socketChannel);  

  16.                 AioSessionConfig sessionConfig = buildSessionConfig(socketChannel);  

  17.                 Session session = new AioTCPSession(sessionConfig,  

  18.                         AioTCPController.this.configuration  

  19.                                 .getSessionReadBufferSize(),  

  20.                         AioTCPController.this.sessionTimeout);  

  21.                 session.start();  

  22.                 registerSession(session);  

  23.             } catch (Exception e) {  

  24.                 e.printStackTrace();  

  25.                 logger.error("Accept error", e);  

  26.                 notifyException(e);  

  27.             } finally {  

  28.                 <strong>pendingAccept</strong>();  

  29.             }  

  30.         }  

  31.   

  32.         @Override  

  33.         public void failed(Throwable exc, Object attachment) {  

  34.             logger.error("Accept error", exc);  

  35.             try {  

  36.                 notifyException(exc);  

  37.             } finally {  

  38.                 <strong>pendingAccept</strong>();  

  39.             }  

  40.         }  

  41.     }  

 

  
    注意到了吧,我們在failed和completed方法中在最後都調用了pendingAccept來繼續發起accept調用,等待新的連接上來。有的同學可能要說了,這樣搞是不是遞歸調用,會不會堆棧溢出?實際上不會,因爲發起accept調用的線程與CompletionHandler回調的線程並非同一個,不是一個上下文中,兩者之間沒有耦合關係。要注意到,CompletionHandler的回調共用的是 AsynchronousChannelGroup綁定的線程池,因此千萬別在CompletionHandler回調方法中調用阻塞或者長時間的操作,例如sleep,回調方法最好能支持超時,防止線程池耗盡。

    連接建立後,怎麼讀和寫呢?回憶下在nonblocking nio框架中,連接建立後的第一件事是幹什麼?註冊OP_READ事件等待socket可讀。異步IO也同樣如此,連接建立後馬上發起一個異步read調用,等待socket可讀,這個是Session.start方法中所做的事情:

Java代碼 複製代碼 收藏代碼

  1. public class AioTCPSession {   

  2.     protected void start0() {   

  3.         pendingRead();   

  4.     }   

  5.   

  6.     protected final void pendingRead() {   

  7.         if (!isClosed() && this.asynchronousSocketChannel.isOpen()) {   

  8.             if (!this.readBuffer.hasRemaining()) {   

  9.                 this.readBuffer = ByteBufferUtils   

  10.                         .increaseBufferCapatity(this.readBuffer);   

  11.             }   

  12.             this.readFuture = this.asynchronousSocketChannel.read(   

  13.                     this.readBuffer, thisthis.readCompletionHandler);   

  14.         } else {   

  15.             throw new IllegalStateException(   

  16.                     "Session Or Channel has been closed");   

  17.         }   

  18.     }   

  19.       

  20. }  

Java代碼  收藏代碼

  1. public class AioTCPSession {  

  2.     protected void start0() {  

  3.         pendingRead();  

  4.     }  

  5.   

  6.     protected final void pendingRead() {  

  7.         if (!isClosed() && this.asynchronousSocketChannel.isOpen()) {  

  8.             if (!this.readBuffer.hasRemaining()) {  

  9.                 this.readBuffer = ByteBufferUtils  

  10.                         .increaseBufferCapatity(this.readBuffer);  

  11.             }  

  12.             this.readFuture = this.asynchronousSocketChannel.read(  

  13.                     this.readBuffer, thisthis.readCompletionHandler);  

  14.         } else {  

  15.             throw new IllegalStateException(  

  16.                     "Session Or Channel has been closed");  

  17.         }  

  18.     }  

  19.      

  20. }  

 

     AsynchronousSocketChannel的read調用與AsynchronousServerSocketChannel的accept調用類似,同樣是非阻塞的,返回結果也是一個Future,但是寫的結果是整數,表示寫入了多少字節,因此read調用返回的是Future<Integer>,方法的第一個參數是讀的緩衝區,操作系統將IO讀到數據拷貝到這個緩衝區,第二個參數是傳遞給 CompletionHandler的attchment,第三個參數就是註冊的用於回調的CompletionHandler。這裏保存了read的結果Future,這是爲了在關閉連接的時候能夠主動取消調用,accept也是如此。現在可以看看read的CompletionHandler的實現:

Java代碼 複製代碼 收藏代碼

  1. public final class ReadCompletionHandler implements  

  2.         CompletionHandler<Integer, AbstractAioSession> {   

  3.   

  4.     private static final Logger log = LoggerFactory   

  5.             .getLogger(ReadCompletionHandler.class);   

  6.     protected final AioTCPController controller;   

  7.   

  8.     public ReadCompletionHandler(AioTCPController controller) {   

  9.         this.controller = controller;   

  10.     }   

  11.   

  12.     @Override  

  13.     public void cancelled(AbstractAioSession session) {   

  14.         log.warn("Session(" + session.getRemoteSocketAddress()   

  15.                 + ") read operation was canceled");   

  16.     }   

  17.   

  18.     @Override  

  19.     public void completed(Integer result, AbstractAioSession session) {   

  20.         if (log.isDebugEnabled())   

  21.             log.debug("Session(" + session.getRemoteSocketAddress()   

  22.                     + ") read +" + result + " bytes");   

  23.         if (result < 0) {   

  24.             session.close();   

  25.             return;   

  26.         }   

  27.         try {   

  28.             if (result > 0) {   

  29.                 session.updateTimeStamp();   

  30.                 session.getReadBuffer().flip();   

  31.                 session.decode();   

  32.                 session.getReadBuffer().compact();   

  33.             }   

  34.         } finally {   

  35.             try {   

  36.                 session.pendingRead();   

  37.             } catch (IOException e) {   

  38.                 session.onException(e);   

  39.                 session.close();   

  40.             }   

  41.         }   

  42.         controller.checkSessionTimeout();   

  43.     }   

  44.   

  45.     @Override  

  46.     public void failed(Throwable exc, AbstractAioSession session) {   

  47.         log.error("Session read error", exc);   

  48.         session.onException(exc);   

  49.         session.close();   

  50.     }   

  51.   

  52. }  

Java代碼  收藏代碼

  1. public final class ReadCompletionHandler implements  

  2.         CompletionHandler<Integer, AbstractAioSession> {  

  3.   

  4.     private static final Logger log = LoggerFactory  

  5.             .getLogger(ReadCompletionHandler.class);  

  6.     protected final AioTCPController controller;  

  7.   

  8.     public ReadCompletionHandler(AioTCPController controller) {  

  9.         this.controller = controller;  

  10.     }  

  11.   

  12.     @Override  

  13.     public void cancelled(AbstractAioSession session) {  

  14.         log.warn("Session(" + session.getRemoteSocketAddress()  

  15.                 + ") read operation was canceled");  

  16.     }  

  17.   

  18.     @Override  

  19.     public void completed(Integer result, AbstractAioSession session) {  

  20.         if (log.isDebugEnabled())  

  21.             log.debug("Session(" + session.getRemoteSocketAddress()  

  22.                     + ") read +" + result + " bytes");  

  23.         if (result < 0) {  

  24.             session.close();  

  25.             return;  

  26.         }  

  27.         try {  

  28.             if (result > 0) {  

  29.                 session.updateTimeStamp();  

  30.                 session.getReadBuffer().flip();  

  31.                 session.decode();  

  32.                 session.getReadBuffer().compact();  

  33.             }  

  34.         } finally {  

  35.             try {  

  36.                 session.pendingRead();  

  37.             } catch (IOException e) {  

  38.                 session.onException(e);  

  39.                 session.close();  

  40.             }  

  41.         }  

  42.         controller.checkSessionTimeout();  

  43.     }  

  44.   

  45.     @Override  

  46.     public void failed(Throwable exc, AbstractAioSession session) {  

  47.         log.error("Session read error", exc);  

  48.         session.onException(exc);  

  49.         session.close();  

  50.     }  

  51.   

  52. }  

 

   如果IO讀失敗,會返回失敗產生的異常,這種情況下我們就主動關閉連接,通過session.close()方法,這個方法幹了兩件事情:關閉channel和取消read調用:

Java代碼 複製代碼 收藏代碼

  1. if (null != this.readFuture) {   

  2.             this.readFuture.cancel(true);   

  3.         }   

  4. this.asynchronousSocketChannel.close();  

Java代碼  收藏代碼

  1. if (null != this.readFuture) {  

  2.             this.readFuture.cancel(true);  

  3.         }  

  4. this.asynchronousSocketChannel.close();  

 

   在讀成功的情況下,我們還需要判斷結果result是否小於0,如果小於0就表示對端關閉了,這種情況下我們也主動關閉連接並返回。如果讀到一定字節,也就是result大於0的情況下,我們就嘗試從讀緩衝區中decode出消息,並派發給業務處理器的回調方法,最終通過pendingRead繼續發起read調用等待socket的下一次可讀。可見,我們並不需要自己去調用channel來進行IO讀,而是操作系統幫你直接讀到了緩衝區,然後給你一個結果表示讀入了多少字節,你處理這個結果即可。而nonblocking IO框架中,是reactor通知用戶線程socket可讀了,然後用戶線程自己去調用read進行實際讀操作。這裏還有個需要注意的地方,就是decode出來的消息的派發給業務處理器工作最好交給一個線程池來處理,避免阻塞group綁定的線程池。
  
   IO寫的操作與此類似,不過通常寫的話我們會在session中關聯一個緩衝隊列來處理,沒有完全寫入或者等待寫入的消息都存放在隊列中,隊列爲空的情況下發起write調用:

Java代碼 複製代碼 收藏代碼

  1. protected void write0(WriteMessage message) {   

  2.       boolean needWrite = false;   

  3.       synchronized (this.writeQueue) {   

  4.           needWrite = this.writeQueue.isEmpty();   

  5.           this.writeQueue.offer(message);   

  6.       }   

  7.       if (needWrite) {   

  8.           pendingWrite(message);   

  9.       }   

  10.   }   

  11.   

  12.   protected final void pendingWrite(WriteMessage message) {   

  13.       message = preprocessWriteMessage(message);   

  14.       if (!isClosed() && this.asynchronousSocketChannel.isOpen()) {   

  15.           this.asynchronousSocketChannel.write(message.getWriteBuffer(),   

  16.                   thisthis.writeCompletionHandler);   

  17.       } else {   

  18.           throw new IllegalStateException(   

  19.                   "Session Or Channel has been closed");   

  20.       }   

  21.   }  

Java代碼  收藏代碼

  1. protected void write0(WriteMessage message) {  

  2.       boolean needWrite = false;  

  3.       synchronized (this.writeQueue) {  

  4.           needWrite = this.writeQueue.isEmpty();  

  5.           this.writeQueue.offer(message);  

  6.       }  

  7.       if (needWrite) {  

  8.           pendingWrite(message);  

  9.       }  

  10.   }  

  11.   

  12.   protected final void pendingWrite(WriteMessage message) {  

  13.       message = preprocessWriteMessage(message);  

  14.       if (!isClosed() && this.asynchronousSocketChannel.isOpen()) {  

  15.           this.asynchronousSocketChannel.write(message.getWriteBuffer(),  

  16.                   thisthis.writeCompletionHandler);  

  17.       } else {  

  18.           throw new IllegalStateException(  

  19.                   "Session Or Channel has been closed");  

  20.       }  

  21.   }  

 

    write調用返回的結果與read一樣是一個Future<Integer>,而write的CompletionHandler處理的核心邏輯大概是這樣:

Java代碼 複製代碼 收藏代碼

  1. @Override  

  2.     public void completed(Integer result, AbstractAioSession session) {   

  3.         if (log.isDebugEnabled())   

  4.             log.debug("Session(" + session.getRemoteSocketAddress()   

  5.                     + ") writen " + result + " bytes");   

  6.                    

  7.         WriteMessage writeMessage;   

  8.         Queue<WriteMessage> writeQueue = session.getWriteQueue();   

  9.         synchronized (writeQueue) {   

  10.             writeMessage = writeQueue.peek();   

  11.             if (writeMessage.getWriteBuffer() == null  

  12.                     || !writeMessage.getWriteBuffer().hasRemaining()) {   

  13.                 writeQueue.remove();   

  14.                 if (writeMessage.getWriteFuture() != null) {   

  15.                     writeMessage.getWriteFuture().setResult(Boolean.TRUE);   

  16.                 }   

  17.                 try {   

  18.                     session.getHandler().onMessageSent(session,   

  19.                             writeMessage.getMessage());   

  20.                 } catch (Exception e) {   

  21.                     session.onException(e);   

  22.                 }   

  23.                 writeMessage = writeQueue.peek();   

  24.             }   

  25.         }   

  26.         if (writeMessage != null) {   

  27.             try {   

  28.                 session.pendingWrite(writeMessage);   

  29.             } catch (IOException e) {   

  30.                 session.onException(e);   

  31.                 session.close();   

  32.             }   

  33.         }   

  34.     }  

Java代碼  收藏代碼

  1. @Override  

  2.     public void completed(Integer result, AbstractAioSession session) {  

  3.         if (log.isDebugEnabled())  

  4.             log.debug("Session(" + session.getRemoteSocketAddress()  

  5.                     + ") writen " + result + " bytes");  

  6.                   

  7.         WriteMessage writeMessage;  

  8.         Queue<WriteMessage> writeQueue = session.getWriteQueue();  

  9.         synchronized (writeQueue) {  

  10.             writeMessage = writeQueue.peek();  

  11.             if (writeMessage.getWriteBuffer() == null  

  12.                     || !writeMessage.getWriteBuffer().hasRemaining()) {  

  13.                 writeQueue.remove();  

  14.                 if (writeMessage.getWriteFuture() != null) {  

  15.                     writeMessage.getWriteFuture().setResult(Boolean.TRUE);  

  16.                 }  

  17.                 try {  

  18.                     session.getHandler().onMessageSent(session,  

  19.                             writeMessage.getMessage());  

  20.                 } catch (Exception e) {  

  21.                     session.onException(e);  

  22.                 }  

  23.                 writeMessage = writeQueue.peek();  

  24.             }  

  25.         }  

  26.         if (writeMessage != null) {  

  27.             try {  

  28.                 session.pendingWrite(writeMessage);  

  29.             } catch (IOException e) {  

  30.                 session.onException(e);  

  31.                 session.close();  

  32.             }  

  33.         }  

  34.     }  

 


   compete方法中的result就是實際寫入的字節數,然後我們判斷消息的緩衝區是否還有剩餘,如果沒有就將消息從隊列中移除,如果隊列中還有消息,那麼繼續發起write調用。

   重複一下,這裏引用的代碼都是yanf4j aio分支中的源碼,感興趣的朋友可以直接check out出來看看:http://yanf4j.googlecode.com/svn/branches/yanf4j-aio
   在引入了aio之後,java對於網絡層的支持已經非常完善,該有的都有了,java也已經成爲服務器開發的首選語言之一。java的弱項在於對內存的管理上,由於這一切都交給了GC,因此在高性能的網絡服務器上還是Cpp的天下。java這種單一堆模型比之erlang的進程內堆模型還是有差距,很難做到高效的垃圾回收和細粒度的內存管理。

   這裏僅僅是介紹了aio開發的核心流程,對於一個網絡框架來說,還需要考慮超時的處理、緩衝buffer的處理、業務層和網絡層的切分、可擴展性、性能的可調性以及一定的通用性要求。

原文:http://lxy2330.iteye.com/blog/1122849


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章