java futuretask get reject异常_FutureTask的get()方法之异常处理

项目中遇到线程池异步处理Callable请求,阻塞接收future.get()结果时,对线程中断状态位state的处理问题。try {

Future 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异常处理亦是如此。

来源:https://www.cnblogs.com/septemberFrost/p/12015029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值