简体   繁体   English

CountDownLatch InterruptedException

[英]CountDownLatch InterruptedException

I am using the CountDownLatch to synchronize an initialization process between two threads and I was wondering about the proper handling of the InterruptedException that it might throw. 我正在使用CountDownLatch来同步两个线程之间的初始化过程,我想知道它可能抛出的InterruptedException的正确处理。

the code i initially wrote was this: 我最初写的代码是这样的:

    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);
            }
        }
    }

Does this pattern make sense? 这种模式有意义吗? Basically is it a good idea to ignore the InterruptedException just keep waiting until it succeeds. 基本上忽略InterruptedException是一个好主意,只需等待它成功。 I guess I just don't understand the situations under which this would get interrupted so I don't know if I should be handling them differently. 我想我只是不明白这会被打断的情况所以我不知道我是否应该以不同的方式处理它们。

Why would an InterruptedException get thrown here, what is the best practice for handling it? 为什么会在这里抛出InterruptedException,处理它的最佳做法是什么?

This is exactly what you should not do for an InterruptedException . 这正是您不应该为InterruptedException做的事情。 An InterruptedException is basically a polite request for that thread to terminate. InterruptedException基本上是该线程终止的礼貌请求。 The thread should clean up and exit as soon as possible. 线程应该尽快清理并退出。

IBM has a good article posted about this: http://www.ibm.com/developerworks/java/library/j-jtp05236.html IBM发表了一篇很好的文章: http//www.ibm.com/developerworks/java/library/j-jtp05236.html

Here's what I would do: 这就是我要做的事情:

// 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.

The advantage to doing it this way is thus: If your thread is interrupted while in a blocking method, the interrupt bit will not be set and an InterruptedException is thrown instead. 这样做的好处是:如果在阻塞方法中线程被中断,则不会设置中断位,而是抛出InterruptedException If your thread is interrupted while not in a blocking method, the interrupted bit will be set, and no exception will be thrown. 如果您的线程在没有阻塞方法的情况下被中断,则将设置被中断的位,并且不会抛出任何异常。 So by calling interrupt() to set the flag on an exception, both cases are being normalized to the first case, which is then checked by the loop conditional. 因此,通过调用interrupt()来设置异常上的标志,两种情况都被标准化为第一种情况,然后由循环条件检查。

As an added bonus, this also lets you stop your thread by simply interrupting it, instead of inventing your own mechanism or interface to set some boolean flag to do the exact same thing. 作为一个额外的好处,这也可以让你通过简单地中断它来停止你的线程,而不是发明你自己的机制或接口来设置一些布尔标志来完成同样的事情。

If you do not foresee any legitimate reason that the Thread could be interrupted, and can't think of any reasonable reaction to it, I'd say you should do 如果你没有预见到Thread可能被打断的任何正当理由,并且无法想到任何合理的反应,我会说你应该这样做

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

That way the application will clearly fail if such interruption happens, making it easier to discover during the testing. 这样,如果发生这种中断,应用程序将明显失败,从而使测试期间更容易发现。 Then you can think about how the application should handle that, or if they are any problem in the design. 然后,您可以考虑应用程序应如何处理,或者它们是否在设计中存在任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM