【问题标题】:wondering why scalaz Task.runAsyncInterruptibly not interrupting as i would expect it to想知道为什么 scalaz Task.runAsyncInterruptibly 没有像我期望的那样中断
【发布时间】:2016-11-26 01:44:36
【问题描述】:

我一直在查看此演示文稿https://github.com/indyscala/scalaz-task-intro/blob/master/presentation.md,并对它使用 Task.runAsyncInterruptibly 演示的代码 sn-ps 之一感到困惑(稍作修改如下所示):

import java.util.concurrent.atomic.AtomicBoolean

import scalaz.concurrent.Task
import scalaz.{-\/, \/-}

object Junk extends App {

  val neverMind = new AtomicBoolean(false)
  System.out.println(s"neverMind set to $neverMind on thread ${Thread.currentThread().getName}")

  val t = Task {
    System.out.println(s" in task run block on thread ${Thread.currentThread().getName}")
    Thread.sleep(4000)
    System.out.println(s" completed sleep of 40000 ms on thread ${Thread.currentThread().getName}")
  }

  Task.fork(t).
  //t.
    runAsyncInterruptibly({
    case -\/(t) => t.printStackTrace()
    case \/-(()) => println(s"Completed (right) branch of case on thread ${Thread.currentThread().getName}")
  }, neverMind)


  println("sleeping 1000, then set nevermind to true")
  Thread.sleep(1000)
  neverMind.set(true)
  println("woke up. set cancel=true -- expect stack trace not 'Completed' message")

  Thread.sleep(4000)

}

我很困惑,因为我设置了“取消”标志 (neverMind.set(true)),但我没有看到堆栈跟踪。延迟 {...} 内的代码块最终打印“成功完成”。这很简单,我确定我犯了一个愚蠢的错误..虽然不知道在哪里!

我曾向一些同事寻求建议,他们指出我的原始示例没有使用 Task.fork() 所以我在同一个线程上做所有事情...... doh!好的。我纠正了这一点。还是不行。

提前感谢您提供的任何指导。

【问题讨论】:

    标签: scala concurrency task scalaz


    【解决方案1】:

    我认为答案与 scalaz 的 Task/Future 中的蹦床有关​​,因为它仅在步骤之间检查 cancel(请参阅 scalaz 的 Future 中的 listenInterruptibly

    如果您将任务更改为:

    val t = Task.delay(System.out.println(s" in task run block on thread ${Thread.currentThread().getName}"))
    .map(_ => Thread.sleep(4000))
    .map(_ => System.out.println(s" completed sleep of 40000 ms on thread ${Thread.currentThread().getName}")) 
    

    您会看到它在“完成睡眠”步骤之前被取消。不过,它似乎仍然没有调用打印堆栈跟踪的处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多