在取消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)的文档说:



如果ForkJoinTasks忽略了中断,您还应该如何检查提交给ForkJoinPool的Callable中的取消?

最佳答案

发生这种情况是因为Future<?>是扩展了ForkJoinTask.AdaptedCallableForkJoinTask,其cancel方法是:

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

它不做任何中断,它只是设置状态。我想发生这种情况是因为ForkJoinPoolsFuture可能具有非常复杂的树结构,并且尚不清楚以哪种顺序取消它们。

10-08 20:22