簡體   English   中英

CountDownLatch InterruptedException

[英]CountDownLatch InterruptedException

我正在使用CountDownLatch來同步兩個線程之間的初始化過程,我想知道它可能拋出的InterruptedException的正確處理。

我最初寫的代碼是這樣的:

    private CountDownLatch initWaitHandle = new CountDownLatch(1);
    /**
     * This method will block until the thread has fully initialized, this should only be called from different threads  Ensure that the thread has started before this is called.
     */
    public void ensureInitialized()
    {
        assert this.isAlive() : "The thread should be started before calling this method.";
        assert Thread.currentThread() != this, "This should be called from a different thread (potential deadlock)";
        while(true)
        {
            try
            {
                //we wait until the updater thread initializes the cache
                //that way we know 
                initWaitHandle.await();
                break;//if we get here the latch is zero and we are done
            } 
            catch (InterruptedException e)
            {
                LOG.warn("Thread interrupted", e);
            }
        }
    }

這種模式有意義嗎? 基本上忽略InterruptedException是一個好主意,只需等待它成功。 我想我只是不明白這會被打斷的情況所以我不知道我是否應該以不同的方式處理它們。

為什么會在這里拋出InterruptedException,處理它的最佳做法是什么?

這正是您不應該為InterruptedException做的事情。 InterruptedException基本上是該線程終止的禮貌請求。 線程應該盡快清理並退出。

IBM發表了一篇很好的文章: http//www.ibm.com/developerworks/java/library/j-jtp05236.html

這就是我要做的事情:

// Run while not interrupted.
while(!(Thread.interrupted())
{
    try
    {
        // Do whatever here.
    }
    catch(InterruptedException e)
    {
        // This will cause the current thread's interrupt flag to be set.
        Thread.currentThread().interrupt();
    }
}

// Perform cleanup and exit thread.

這樣做的好處是:如果在阻塞方法中線程被中斷,則不會設置中斷位,而是拋出InterruptedException 如果您的線程在沒有阻塞方法的情況下被中斷,則將設置被中斷的位,並且不會拋出任何異常。 因此,通過調用interrupt()來設置異常上的標志,兩種情況都被標准化為第一種情況,然后由循環條件檢查。

作為一個額外的好處,這也可以讓你通過簡單地中斷它來停止你的線程,而不是發明你自己的機制或接口來設置一些布爾標志來完成同樣的事情。

如果你沒有預見到Thread可能被打斷的任何正當理由,並且無法想到任何合理的反應,我會說你應該這樣做

 catch (InterruptedException e){
      throw new AssertionError("Unexpected Interruption",e);
 }

這樣,如果發生這種中斷,應用程序將明顯失敗,從而使測試期間更容易發現。 然后,您可以考慮應用程序應如何處理,或者它們是否在設計中存在任何問題。

暫無
暫無

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

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