ForkJoinPool重置线程中断状态

时间:2014-01-23 21:55:27

标签: java multithreading java.util.concurrent forkjoinpool

我在取消ForkJoinPool返回的Future时发现了以下现象。给出以下示例代码:

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);

程序永远不会打印interruptedForkJoinTask#cancel(boolean)的文档说:

  

mayInterruptIfRunning - 此值在默认实现中无效,因为中断不用于控制取消。

如果ForkJoinTasks忽略了中断,你应该如何在提交给ForkJoinPool的Callables中检查取消?

1 个答案:

答案 0 :(得分:5)

这是因为Future<?>ForkJoinTask.AdaptedCallable,其扩展ForkJoinTask,其取消方法为:

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的{​​{1}}可能有一个非常复杂的树结构,并且不清楚取消它们的顺序。