您應該清楚地將異步管道設計爲具有數據/事件依賴關係的圖形。典型的圖形包括兩種節點的:
fast handler:
immediately invoked when an event happens and:
probably stores the event,
and/or calls another fast handler,
and/or submits an asynchronous task to an executor
task:
runs and issues events (that is, calls fast handlers)
所以基本上你需要開發兩個獨立的層:快速處理程序和任務執行。執行程序是通用的,可以從java.util.concurrent包中獲取。快速處理程序很大程度上取決於您的問題域,並且不存在適用於所有情況的通用庫。例如,純隊列是一個快速處理程序,它只存儲事件,因此幾乎是無用的。
如果您使用I/O,則需要使用標準I/O庫,以便它們爲您的處理程序發出I/O事件。它可以使用同步I/O的線程構建,也可以使用Selector線程或異步I/O的異步通道構建。與NIO2異步通道使用
快速處理程序例如:
class ConnectionAcceptor implements CompletionHandler<AsynchronousSocketChannel, Void>{
AsynchronousServerSocketChannel assc;
int maxConn;// max number of simultaneous connections
int connCount=0;
/* called on creation to start listening incoming client connection requests */
void allowAccept() {
assc.accept(null, this);
}
/* called by I/O layer when a client connection requested */
public synchronized void completed(AsynchronousSocketChannel result, Void attachment) {
executor.exec(new Connection(result));
connCount++;
if (connCount<maxConn) {
allowAccept();
}
}
/* called by Connection when it is closed */
synchronized void connClosed() {
if (connCount==maxConn) {
allowAccept();
}
connCount--;
}
}
該處理器具有3個入口點和處理3類型的事件。相似的,處理器可以創建讀或寫(但不是兩者)。它的內部狀態不是connCount,而是包含一個指示I/O操作正在進行的布爾標誌,以及等待AsynchronousSocketChannel結束啓動操作的緩衝區隊列。
['FutureTask'](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html):「一個可取消的異步計算。」 – 2rs2ts