(二) 理解AsynchronousChannelGroup

這一陣子研究JAVA7的AIO,也就是NIO2,網上有很多關於NIO1和NIO2的介紹。

 

簡單說來,在AIO中,操作系統爲我們做了更多的事情。因爲操作系統更底層,所以理論上來講效率會更高些。

 

AsynchronousChannelGroup可以理解爲一個JVM中對於Socket相關操作的一些公共資源的代表。

 

一個ChannelGroup和一個(或2個)thread pool關聯。

 

理解AsynchronousChannelGroup 

首先引用PRO JAVA 7 NIO2書中的一段話,來解釋一下AsynchronousChannelGroup的幾個關鍵點。

 寫道
the asynchronous API introduces a class named AsynchronousChannelGroup, which presents the concept of an asynchronous channel group , in which each asynchronous channel belongs to a channel group (the default one or a specified one) that shares a pool of Java threads. These threads receive instruct ions to perform I/O events and they dispatch the results to the completion handlers. The asynchronous channel group encapsulat es thread pool and the resources shared by all the threads working for the channels. Also, the channel is in effect owned by the group, so if the group is closed, the channel is closed too.

 

首先,每一個asynchronous channel都屬於同一個group,共享一個Java線程池

 

1. 從代碼創建角度來看無論是AsynchronousServerSocketChannel還是AsynchronousSocketChannel的創建都使用各自的靜態方法open,而open方法便需要asynchronousChannelGroup。

 

2. 可以發現AsynchronousChannelGroup其內部其實是一個(一些)線程池來進行實質工作的;而他們乾的活就是等待IO事件,處理數據,分發各個註冊的completion handlers

 

其次便是NIO與NIO2的區別了

即REACTOR PROACTOR,同步IO和異步IO

 

在同步IO中等待IO事件由我們註冊的selector來完成,在感興趣的事情來了,我們的線程來accept.read.write.connect...幹活,幹好後再交由業務邏輯處理。

 

在異步IO中等待IO事件同樣爲acceptor,read,write,connect,但數據處理交由系統完成,我們需要做的就是在completion handlers中處理業務邏輯。

 

誰來幹以前的活

 

是時候來想想NIO中(最樸素的),我們通常要幹兩件比較底層的事情

 

1. 弄一個seletor,在他身上註冊各種感興趣的事件,然後select,等待感興趣的事情發生

 

2. 感興趣的事情發生了,比如可以讀了,這時便需要我們的線程從channel中讀數據到bytebuffer裏

 

那麼在AIO裏,這些都不需要了,因爲系統替你做好了!

 

但是,系統替你做的事是2,系統級的AIO,windows下的iocp(真AIO),linux下的epoll(模擬)

 

那1這個事情其實還是要由java的線程去做,所以我們還是需要一個類似seletor的存在,他就是我們提供的AsynchronousChannelGroup中的線程池。

 

 

下篇中將詳細講述AsynchronousChannelGroup的創建及各自的特點。

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