JAVA併發包 Future 解讀

併發包 Future 解讀


java 併發包 java.util.concurrent 有很多關於併發編程相關的類
屏蔽了操作系統的調度 友好的提供了API 便於技術大大更高效 快捷的使用多核心 提高應用的響應耗時 提升性能

Future 官方文檔

future 是一個 異步計算的類。提供了檢查計算是否完成、等待其完成並檢索計算結果的方法。

應用場景

應用中的列表查詢 是一個很常見的業務場景.一般來說 會有2種查詢
1.查詢當前分頁的數據
2.查詢當前條件的數據總數 計算分頁
常用的寫法就是
ex:
List result = queryList(params);
int count = queryListCount(params);
這裏很明顯是個串行的操作.如果都是耗時的操作 那麼整個請求的耗時就是2個查詢的疊加
那麼 如果使用Future 異步方式呢.
那麼時間耗時 就不是串行的操作 而是個並行的操作.
ex:
/* 啓動一個新的線程去執行 /
Future future = Executors.newFixedThreadPool().submit(new Callback()
public String call() {
return queryListCount(params);
});
/* 主線程執行 /
List result = queryList(params);
int count = future.get(time,TimeUnit);
這樣的話 就能減小整個請求的耗時

Future 是怎麼做到的?

Future 只是個接口 常用的實現類是 FutureTask java.util.concurrent 包下面的

public class FutureTask<V> implements RunnableFuture<V> {
        /** 只貼出比較重要的方法 */
        public void run() {
        /** 判斷當前執行狀態 */
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    /** 線程等待處理完成 */
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                /** 如果處理完成 就回寫結果 */
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

        /**
         * 獲取數據操作時候 一直進行cas操作 判斷任務狀態
         */
        public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
             /** 阻塞線程 */
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

    /**
     * run 方法執行完成 會通過set方法給outcome 賦值
     */
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

    /**
     * 利用CAS操作 阻塞線程 返回當前任務狀態
     * 
     */
    private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        /** 死循環 一直嘗試獲取state狀態 */
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            /** 如果狀態完成 就讓出線程佔用的硬件資源 */
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);         
            else if (timed) {
                /** 如果等待時間消耗完了 就直接返回了 */
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                /** 線程阻塞nanos毫秒 */
                LockSupport.parkNanos(this, nanos);
            }
            else
                /** 線程一直阻塞 */
                LockSupport.park(this);
        }
    }
}

大家通過註釋 應該能瞭解到 future 是怎麼實現異步化的了.

就是利用 cas操作判斷future內部對象的state狀態是否達到完成

超時就拋出一個 timeOut異常

其實 從這裏可以看出就算最後拋出異常了 run方法還是會執行下去的.

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