我正在使用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,如何最佳实践处理它?