ForkJoinPool重置线程中断状态 [英] ForkJoinPool resets thread interrupted state

查看:331
本文介绍了ForkJoinPool重置线程中断状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当取消 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)说:

mayInterruptIfRunning-该值在默认实现中无效,因为不使用中断来控制取消.

mayInterruptIfRunning - this value has no effect in the default implementation because interrupts are not used to control cancellation.

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

If ForkJoinTasks ignore interrupts, how else are you supposed to check for cancellation inside Callables submitted to a ForkJoinPool?

推荐答案

之所以会发生这种情况,是因为Future<?>是扩展了ForkJoinTaskForkJoinTask.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;
        }
    }
}

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

It does not do any interruptions, it just sets status. I suppose this happens becouse ForkJoinPools's Futures might have a very complicated tree structure, and it is unclear in which order to cancel them.

这篇关于ForkJoinPool重置线程中断状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆