FutureTask的get()方法之异常处理


项目中遇到线程池异步处理Callable请求,阻塞接收future.get()结果时,对线程中断状态位state的处理问题。
try {
  Future<Object> future = executor.submit(callcable);
  future.get();
} catch (InterruptedException e) {
  Thread.interrupted(); // 重置当前线程的中断位state为false,便于该线程以后被其他任务正常调用
}
对项目中的这种处理感到疑惑,翻了下源码中具体的实现细节,发现Future的实现类FutureTask的get()方法如下:
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L); // throws InterruptedException
    return report(s); // throws ExecutionException
}

其中InterruptedException是awaitDone(false, 0L)方法抛出的:
if (Thread.interrupted()) {
    removeWaiter(q);
    throw new InterruptedException();
}

可以看出awaitDone(boolean timed, long nanos)方法中已经重置了状态位state,所以正常项目中捕获InterruptedException异常后,不需要再重新重置当前线程的状态位state。
不过为了安全保险起见,Thread.interrupted()重置一下会更加便于项目中的理解;
同时Process的实现类ProcessImpl的waitFor()抛出的InterruptedException异常处理亦是如此。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM