簡體   English   中英

Java:帶有Callables的ExecutorService:Timeout:future.get()導致程序的直接中斷

[英]Java: ExecutorService with Callables: Timeout: future.get() leads to direct break of program

我在Java中使用ExecutorService,我注意到了一個我不理解的行為。 我使用Callable,當我調用我的線程(實現Callable的類)時,我設置了一個超時。 那我等與結果future.get()后,我想檢查用future.isDone()如果執行任務期間發生超時。

正如我在帶有超時的invokeAll文檔中所讀到的那樣: returns 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. returns 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.

所以我想我會在兩種情況下獲得Future結果列表,如果發生超時,如果沒有。

現在會發生什么是這樣的:當超時發生時,該代碼后不下去future.get()我不曾經得到的地方,如果有發生超時,我可以檢查點future.isDone() 我沒有發現任何異常,我直接導致我的代碼中的finally塊,我真的不明白。

這是我的代碼片段:

     try {
        // start all Threads
        results = pool.invokeAll(threads, 3, TimeUnit.SECONDS);

        for (Future<String> future : results)
        {
            try
            {
                // this method blocks until it receives the result, unless there is a 
                // timeout set.
                final String rs = future.get();

                if (future.isDone())
                {
                    // if future.isDone() = true, a timeout did not occur. 
                   // do something
                }
                else
                {
                    // timeout
                    // log it and do something
                    break;
                }
            }
            catch (ExecutionException e)
            {
               // log messages and break, this is a snippet!
            }
            catch (InterruptedException ex)
            {
               // log message and break, this is a snippet!
            }
        }

    }
    catch (InterruptedException ex)
    {
        // log message, this is a snippet!
    }
    finally
    {
        // when a timeout occurs, the code jumps from future.get() directly to this point!
    }

可能有人解釋我,為什么我無法達到future.isDone()以及我應該改變什么才能識別超時?

謝謝!

你沒有捕獲CancellationException ,這很可能在調用get后被拋出。 請注意,此異常會擴展RuntimeException ,編譯器不會警告您捕獲它。

閱讀invokeAll的文檔:

執行給定的任務,返回一個Futures列表,其中包含所有完成或超時到期時的狀態和結果,以先發生者為准。 對於返回列表的每個元素,Future.isDone()都為true。 返回時, 未完成的任務將被取消

我不確定你是否正確使用invokeAll javadoc說:

執行給定的任務,返回一個Futures列表,其中包含所有完成或超時到期時的狀態和結果,以先發生者為准。 對於返回列表的每個元素,Future.isDone()都為true。

那么,什么是調用點isDone因為所有期貨交易返回isDone是真的嗎?

使用isCancelled。 如果為false,則表示沒有超時。 然后你可以調用get()並捕獲executionException如果任務沒有超時但由於任何其他原因(例如nullpointer,assert等)而有異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM