问题描述
当取消 ForkJoinPool .给出以下示例代码:
I just noticed the following phenomena when cancelling a Future returned by ForkJoinPool. Given the following example code:
ForkJoinPool pool = new ForkJoinPool();
Future<?> fut = pool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
while (true) {
if (Thread.currentThread().isInterrupted()) { // <-- never true
System.out.println("interrupted");
throw new InterruptedException();
}
}
}
});
Thread.sleep(1000);
System.out.println("cancel");
fut.cancel(true);
程序从不打印interrupted
. ForkJoinTask#的文档cancel(boolean)说:
如果ForkJoinTasks忽略了中断,您还应该如何检查提交给ForkJoinPool的Callable中的取消?
If ForkJoinTasks ignore interrupts, how else are you supposed to check for cancellation inside Callables submitted to a ForkJoinPool?
推荐答案
之所以会发生这种情况,是因为Future<?>
是扩展了ForkJoinTask
的ForkJoinTask.AdaptedCallable
,其取消方法是:
This happens because Future<?>
is a ForkJoinTask.AdaptedCallable
which extends ForkJoinTask
, whose cancel method is:
public boolean cancel(boolean mayInterruptIfRunning) {
return setCompletion(CANCELLED) == CANCELLED;
}
private int setCompletion(int completion) {
for (int s;;) {
if ((s = status) < 0)
return s;
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
if (s != 0)
synchronized (this) { notifyAll(); }
return completion;
}
}
}
它不做任何打扰,它只是设置状态.我想发生这种情况是因为ForkJoinPools
的Future
可能具有非常复杂的树结构,并且尚不清楚取消它们的顺序.
It does not do any interruptions, it just sets status. I suppose this happens becouse ForkJoinPools
's Future
s might have a very complicated tree structure, and it is unclear in which order to cancel them.
这篇关于ForkJoinPool重置线程中断状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!