Java那點事——異步
在JDK1.6提供了Future,FutureTask,ExecutorService等用于支持異步編程,但是Future,FutureTask沒有提供callback機制,只能主動輪詢,通過get去獲取結果。
Guava的ListenableFuture對此做了擴展,支持callback機制。
就callback機制的擴展而言,也并不復雜。看看ListenableFuture與ListenableFutureTask:
public interface ListenableFuture extends Future { void addListener(Runnable listener, Executor executor); } public class ListenableFutureTask extends FutureTask implements ListenableFuture { // The execution list to hold our listeners. private final ExecutionList executionList = new ExecutionList(); //……… @Override public void addListener(Runnable listener, Executor exec) { executionList.add(listener, exec); } /** * Internal implementation detail used to invoke the listeners. */ @Override protected void done() { executionList.execute(); } }
callback通過addListener添加,通過override FutureTask的done()函數實現回調。 查看FutureTask會在Task執行完以后調用done()函數,如:
/** * Removes and signals all waiting threads, invokes done(), and * nulls out callable. */ private void finishCompletion() { // assert state > COMPLETING; for (WaitNode q; (q = waiters) != null;) { if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { for (;;) { Thread t = q.thread; if (t != null) { q.thread = null; LockSupport.unpark(t); } WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } } done(); callable = null; // to reduce footprint }
與JDK一樣,ListenableFuture需要通過ExecutorService創建,Guava定義了對應的ExecutorService,并提供MoreExecutors作為工具類,其中實現了ListeningDecorator與ScheduledListeningDecorator,它們都是對應的JDK ExecutorService的裝飾。MoreExecutors提供的工具api非常很多,需要細細瞧瞧。
1.8版本開始,JDK也開始提供了一些更好支持異步編程的Future,典型的有CompletableFuture.
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!