forkjoinpool重置线程中断状态



我只是在取消Forkjoinpool返回的未来时注意到了以下现象。给定以下示例代码:

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#取消(布尔值)的文档说:

MayInterruptifrunning-此值在默认实现中没有影响,因为中断不用于控制取消。

如果forkjointask忽略了中断,您还应该如何检查提交给forkjoinpool的可呼叫内部的取消?

发生这种情况,因为 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;
        }
    }
}

它不进行任何干扰,而只是设置状态。我想这发生了,因为ForkJoinPoolsFuture s可能具有非常复杂的树结构,并且尚不清楚要取消它们的顺序。

在@mkhail的顶部共享更多灯:

使用forkjoinpool execute()而不是crist()将迫使失败的运行以抛出一个worker例外,将被TREED uncaughtexceptionhandler抓住。。

从Java 8代码中取出:
提交使用AdaptedRunnableAction()。
Execute使用RunnableExecuteAction()(请参阅 rethrow(ex))。

 /**
 * Adaptor for Runnables without results
 */
static final class AdaptedRunnableAction extends ForkJoinTask<Void>
    implements RunnableFuture<Void> {
    final Runnable runnable;
    AdaptedRunnableAction(Runnable runnable) {
        if (runnable == null) throw new NullPointerException();
        this.runnable = runnable;
    }
    public final Void getRawResult() { return null; }
    public final void setRawResult(Void v) { }
    public final boolean exec() { runnable.run(); return true; }
    public final void run() { invoke(); }
    private static final long serialVersionUID = 5232453952276885070L;
}
/**
 * Adaptor for Runnables in which failure forces worker exception
 */
static final class RunnableExecuteAction extends ForkJoinTask<Void> {
    final Runnable runnable;
    RunnableExecuteAction(Runnable runnable) {
        if (runnable == null) throw new NullPointerException();
        this.runnable = runnable;
    }
    public final Void getRawResult() { return null; }
    public final void setRawResult(Void v) { }
    public final boolean exec() { runnable.run(); return true; }
    void internalPropagateException(Throwable ex) {
        rethrow(ex); // rethrow outside exec() catches.
    }
    private static final long serialVersionUID = 5232453952276885070L;
}

最新更新