CountDownLatch InterruptedException

luk*_*uke 11 java multithreading exception-handling

我正在使用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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这种模式有意义吗?基本上忽略InterruptedException是一个好主意,只需等待它成功.我想我只是不明白这会被打断的情况所以我不知道我是否应该以不同的方式处理它们.

为什么会在这里抛出InterruptedException,处理它的最佳做法是什么?

jdm*_*hal 9

这正是你不应该做的InterruptedException.An 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.
Run Code Online (Sandbox Code Playgroud)

这样做的好处是:如果在阻塞方法中线程被中断,则不会设置中断位InterruptedException而是抛出一个中断位.如果您的线程在没有阻塞方法的情况下被中断,则将设置被中断的位,并且不会抛出任何异常.因此,通过调用interrupt()在异常上设置标志,两种情况都被标准化为第一种情况,然后由循环条件检查.

作为一个额外的好处,这也可以让你通过简单地中断它来停止你的线程,而不是发明你自己的机制或接口来设置一些布尔标志来完成同样的事情.