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

China☆狼群 提交于 2019-12-10 10:23:33
项目中遇到线程池异步处理Callable请求,阻塞接收future.get()结果时,对线程中断状态位state的处理问题。try {
  Future<Object> future = executor.submit(callcable);
  future.get();
} catch (InterruptedException e) {
  Thread.interrupted(); // 重置当前线程的中断位state为true,便于该线程以后被其他任务正常调用
}
对项目中的这种处理感到疑惑,翻了下源码中具体的实现细节,发现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异常处理亦是如此。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!