[英]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.