Java中的Future

1 概述

Future代表異步計(jì)算返回的結(jié)果祭椰,提供了檢查是否結(jié)束蒲讯、等待結(jié)束以及獲取計(jì)算結(jié)果的方法垫蛆。Executor框架使用Runnable作為其任務(wù)表示形式违孝,但它不能返回一個值府蛇。許多任務(wù)實(shí)際上都是存在延遲計(jì)算的:執(zhí)行數(shù)據(jù)庫查詢集索,從網(wǎng)絡(luò)上獲取資源,或者某個復(fù)雜耗時的計(jì)算汇跨。對于這種任務(wù)务荆,Callable是一個更好的抽象,他能返回一個值穷遂,并可能拋出一個異常函匕。

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * <tt>call</tt>.
 *
 * <p>The <tt>Callable</tt> interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * <tt>Runnable</tt>, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p> The {@link Executors} class contains utility methods to
 * convert from other common forms to <tt>Callable</tt> classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method <tt>call</tt>
 */
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
public interface Future<V> {

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when <tt>cancel</tt> is called,
     * this task should never run.  If the task has already started,
     * then the <tt>mayInterruptIfRunning</tt> parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return <tt>true</tt>.  Subsequent calls to {@link #isCancelled}
     * will always return <tt>true</tt> if this method returned <tt>true</tt>.
     *
     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return <tt>false</tt> if the task could not be cancelled,
     * typically because it has already completed normally;
     * <tt>true</tt> otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns <tt>true</tt> if this task was cancelled before it completed
     * normally.
     *
     * @return <tt>true</tt> if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns <tt>true</tt> if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * <tt>true</tt>.
     *
     * @return <tt>true</tt> if this task completed
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

可以通過多種方法來創(chuàng)建一個Future來描述任務(wù)。ExecutorService中的submit方法接受一個Runnable或者Callable蚪黑,然后返回一個Future來獲得任務(wù)的執(zhí)行結(jié)果或者取消任務(wù)盅惜。

public interface ExecutorService extends Executor {

   /**
    * Submits a value-returning task for execution and returns a
    * Future representing the pending results of the task. The
    * Future's <tt>get</tt> method will return the task's result upon
    * successful completion.
    *
    * <p>
    * If you would like to immediately block waiting
    * for a task, you can use constructions of the form
    * <tt>result = exec.submit(aCallable).get();</tt>
    *
    * <p> Note: The {@link Executors} class includes a set of methods
    * that can convert some other common closure-like objects,
    * for example, {@link java.security.PrivilegedAction} to
    * {@link Callable} form so they can be submitted.
    *
    * @param task the task to submit
    * @return a Future representing pending completion of the task
    * @throws RejectedExecutionException if the task cannot be
    *         scheduled for execution
    * @throws NullPointerException if the task is null
    */
   <T> Future<T> submit(Callable<T> task);

   /**
    * Submits a Runnable task for execution and returns a Future
    * representing that task. The Future's <tt>get</tt> method will
    * return the given result upon successful completion.
    *
    * @param task the task to submit
    * @param result the result to return
    * @return a Future representing pending completion of the task
    * @throws RejectedExecutionException if the task cannot be
    *         scheduled for execution
    * @throws NullPointerException if the task is null
    */
   <T> Future<T> submit(Runnable task, T result);

   /**
    * Submits a Runnable task for execution and returns a Future
    * representing that task. The Future's <tt>get</tt> method will
    * return <tt>null</tt> upon <em>successful</em> completion.
    *
    * @param task the task to submit
    * @return a Future representing pending completion of the task
    * @throws RejectedExecutionException if the task cannot be
    *         scheduled for execution
    * @throws NullPointerException if the task is null
    */
   Future<?> submit(Runnable task);

   /**
    * Executes the given tasks, returning a list of Futures holding
    * their status and results when all complete.
    * {@link Future#isDone} is <tt>true</tt> for each
    * element of the returned list.
    * Note that a <em>completed</em> task could have
    * terminated either normally or by throwing an exception.
    * The results of this method are undefined if the given
    * collection is modified while this operation is in progress.
    *
    * @param tasks the collection of tasks
    * @return A list of Futures representing the tasks, in the same
    *         sequential order as produced by the iterator for the
    *         given task list, each of which has completed.
    * @throws InterruptedException if interrupted while waiting, in
    *         which case unfinished tasks are cancelled.
    * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
    * @throws RejectedExecutionException if any task cannot be
    *         scheduled for execution
    */

   <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
       throws InterruptedException;

   /**
    * Executes the given tasks, returning a list of Futures holding
    * their status and results
    * when all complete or the timeout expires, whichever happens first.
    * {@link Future#isDone} is <tt>true</tt> for each
    * element of the returned list.
    * Upon return, tasks that have not completed are cancelled.
    * Note that a <em>completed</em> task could have
    * terminated either normally or by throwing an exception.
    * The results of this method are undefined if the given
    * collection is modified while this operation is in progress.
    *
    * @param tasks the collection of tasks
    * @param timeout the maximum time to wait
    * @param unit the time unit of the timeout argument
    * @return a list of Futures representing the tasks, in the same
    *         sequential order as produced by the iterator for the
    *         given task list. If the operation did not time out,
    *         each task will have completed. If it did time out, some
    *         of these tasks will not have completed.
    * @throws InterruptedException if interrupted while waiting, in
    *         which case unfinished tasks are cancelled
    * @throws NullPointerException if tasks, any of its elements, or
    *         unit are <tt>null</tt>
    * @throws RejectedExecutionException if any task cannot be scheduled
    *         for execution
    */
   <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                 long timeout, TimeUnit unit)
       throws InterruptedException;

   /**
    * Executes the given tasks, returning the result
    * of one that has completed successfully (i.e., without throwing
    * an exception), if any do. Upon normal or exceptional return,
    * tasks that have not completed are cancelled.
    * The results of this method are undefined if the given
    * collection is modified while this operation is in progress.
    *
    * @param tasks the collection of tasks
    * @return the result returned by one of the tasks
    * @throws InterruptedException if interrupted while waiting
    * @throws NullPointerException if tasks or any element task
    *         subject to execution is <tt>null</tt>
    * @throws IllegalArgumentException if tasks is empty
    * @throws ExecutionException if no task successfully completes
    * @throws RejectedExecutionException if tasks cannot be scheduled
    *         for execution
    */
   <T> T invokeAny(Collection<? extends Callable<T>> tasks)
       throws InterruptedException, ExecutionException;

   /**
    * Executes the given tasks, returning the result
    * of one that has completed successfully (i.e., without throwing
    * an exception), if any do before the given timeout elapses.
    * Upon normal or exceptional return, tasks that have not
    * completed are cancelled.
    * The results of this method are undefined if the given
    * collection is modified while this operation is in progress.
    *
    * @param tasks the collection of tasks
    * @param timeout the maximum time to wait
    * @param unit the time unit of the timeout argument
    * @return the result returned by one of the tasks.
    * @throws InterruptedException if interrupted while waiting
    * @throws NullPointerException if tasks, or unit, or any element
    *         task subject to execution is <tt>null</tt>
    * @throws TimeoutException if the given timeout elapses before
    *         any task successfully completes
    * @throws ExecutionException if no task successfully completes
    * @throws RejectedExecutionException if tasks cannot be scheduled
    *         for execution
    */
   <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                   long timeout, TimeUnit unit)
       throws InterruptedException, ExecutionException, TimeoutException;
}

假設(shè)我們通過一個方法從遠(yuǎn)程獲取一些計(jì)算結(jié)果,假設(shè)方法是List getDataFromRemote()忌穿,如果采用同步的方法抒寂,代碼大概是List data = getDataFromRemote(),我們將一直等待getDataFromRemote返回,然后才能繼續(xù)后面的工作掠剑,這個函數(shù)是從遠(yuǎn)程獲取計(jì)算結(jié)果的屈芜,如果需要很長時間,后面的代碼又和這個數(shù)據(jù)沒有什么關(guān)系的話朴译,阻塞在那里就會浪費(fèi)很多時間井佑。我們有什么辦法可以改進(jìn)呢?动分?毅糟?

能夠想到的辦法是調(diào)用函數(shù)后,立即返回澜公,然后繼續(xù)執(zhí)行姆另,等需要用數(shù)據(jù)的時候喇肋,再取或者等待這個數(shù)據(jù)。具體實(shí)現(xiàn)有兩種方式迹辐,一個是用Future蝶防,另一個是回調(diào)。

Future<List> future = getDataFromRemoteByFuture();
        //do something....
List data = future.get();

可以看到我們返回的是一個Future對象明吩,然后接著自己的處理后面通過future.get()來獲得我們想要的值间学。也就是說在執(zhí)行g(shù)etDataFromRemoteByFuture的時候,就已經(jīng)啟動了對遠(yuǎn)程計(jì)算結(jié)果的獲取印荔,同時自己的線程還繼續(xù)執(zhí)行不阻塞低葫。知道獲取時候再拿數(shù)據(jù)就可以∪月桑看一下getDataFromRemoteByFuture的實(shí)現(xiàn):

private Future<List> getDataFromRemoteByFuture() {

        return threadPool.submit(new Callable<List>() {
            @Override
            public List call() throws Exception {
                return getDataFromRemote();
            }
        });
    }

我們在這個方法中調(diào)用getDataFromRemote方法嘿悬,并且用到了線程池。把任務(wù)加入線程池之后水泉,理解返回Future對象善涨。Future的get方法,還可以傳入一個超時參數(shù)草则,用來設(shè)置等待時間钢拧,不會一直等下去。
也可以利用FutureTask來獲取結(jié)果:

FutureTask<List> futureTask = new FutureTask<List>(new Callable<List>() {
            @Override
            public List call() throws Exception {
                return getDataFromRemote();
            }
        });

        threadPool.submit(futureTask);


        futureTask.get();

FutureTask是一個具體的實(shí)現(xiàn)類炕横,ThreadPoolExecutor的submit方法返回的就是一個Future的實(shí)現(xiàn)源内,這個實(shí)現(xiàn)就是FutureTask的一個具體實(shí)例,F(xiàn)utureTask幫助實(shí)現(xiàn)了具體的任務(wù)執(zhí)行看锉,以及和Future接口中的get方法的關(guān)聯(lián)姿锭。FutureTask除了幫助ThreadPool很好的實(shí)現(xiàn)了對加入線程池任務(wù)的Future支持外,也為我們提供了很大的便利伯铣,使得我們自己也可以實(shí)現(xiàn)支持Future的任務(wù)調(diào)度呻此。

Java本身沒有提供Promise方式實(shí)現(xiàn),在Scala以及Netty中都有Promise模式的實(shí)現(xiàn)腔寡,可以讓用戶控制future的完成狀態(tài)(成功焚鲜、失敗等)以及future的返回值,參考文檔中是一個自定義Promise的簡單實(shí)現(xiàn)放前。

Reference

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末忿磅,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子凭语,更是在濱河造成了極大的恐慌葱她,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件似扔,死亡現(xiàn)場離奇詭異吨些,居然都是意外死亡搓谆,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進(jìn)店門豪墅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泉手,“玉大人,你說我怎么就攤上這事偶器≌睹龋” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵屏轰,是天一觀的道長颊郎。 經(jīng)常有香客問我,道長亭枷,這世上最難降的妖魔是什么袭艺? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任搀崭,我火速辦了婚禮叨粘,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘瘤睹。我一直安慰自己升敲,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布轰传。 她就那樣靜靜地躺著驴党,像睡著了一般。 火紅的嫁衣襯著肌膚如雪获茬。 梳的紋絲不亂的頭發(fā)上港庄,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天,我揣著相機(jī)與錄音恕曲,去河邊找鬼鹏氧。 笑死,一個胖子當(dāng)著我的面吹牛佩谣,可吹牛的內(nèi)容都是我干的把还。 我是一名探鬼主播,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼茸俭,長吁一口氣:“原來是場噩夢啊……” “哼吊履!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起调鬓,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤艇炎,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后腾窝,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缀踪,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡腺晾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了辜贵。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片悯蝉。...
    茶點(diǎn)故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖托慨,靈堂內(nèi)的尸體忽然破棺而出鼻由,到底是詐尸還是另有隱情,我是刑警寧澤厚棵,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布蕉世,位于F島的核電站,受9級特大地震影響婆硬,放射性物質(zhì)發(fā)生泄漏狠轻。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一彬犯、第九天 我趴在偏房一處隱蔽的房頂上張望向楼。 院中可真熱鬧,春花似錦谐区、人聲如沸湖蜕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽昭抒。三九已至,卻和暖如春炼杖,著一層夾襖步出監(jiān)牢的瞬間灭返,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工坤邪, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留熙含,地道東北人。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓罩扇,卻偏偏與公主長得像婆芦,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子喂饥,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容