倒计时闩锁中断异常
2022-09-04 02:54:04
我正在使用CountDownLatch在两个线程之间同步初始化过程,我想知道它可能引发的DistrutedException的正确处理。
我最初写的代码是这样的:
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);
}
}
}
这种模式有意义吗?基本上,忽略中断异常是一个好主意,只是继续等待,直到它成功。我想我只是不明白这种情况会被打断,所以我不知道我是否应该以不同的方式处理它们。
为什么会在这里抛出一个中断异常,处理它的最佳实践是什么?