scala - 使用 future 时程序不会终止

标签 scala file concurrency future

我正在尝试对目录中的每个文件同时运行一个函数。可悲的是,每当我使用 Futures 时,我的程序都不想终止(永远运行)。我试过使用 Await.result()结果相同:/
运行代码时它执行得很好,甚至“完成?”被打印,然后它挂起......
继承人我的代码。 (我是 Scala 的新手)

val execService = Executors.newFixedThreadPool(3)
implicit val execContext = ExecutionContext.fromExecutorService(execService)

val futures = for (file <- filesList) yield Future {
   println(file)
   // theFunc(file)
}
val seq = Future.sequence(futures)
seq.onComplete {
   case Success(x) => println("finish?")
   case Failure(e) => println(e)
}

最佳答案

Executors.newFixedThreadPool引擎盖下使用 defaultThreadFactory 创建非守护线程

Returns a default thread factory used to create new threads. This factory creates all new threads used by an Executor in the same ThreadGroup... Each new thread is created as a non-daemon thread


因为这些是非守护线程,所以程序不会终止。另一方面,例如,scala.concurrent.ExecutionContext.Implicits.global创建 daemon线程
val threadFactory = new DefaultThreadFactory(daemonic = true,
                                             maxBlockers = getInt("scala.concurrent.context.maxExtraThreads", "256"),
                                             prefix = "scala-execution-context-global",
                                             uncaught = (thread: Thread, cause: Throwable) => reporter(cause))
我们注意到的地方 daemonic = true ,所以下面的程序会在最后终止
implicit val execContext = scala.concurrent.ExecutionContext.Implicits.global

val futures = for (file <- filesList) yield Future {
   println(file)
   // theFunc(file)
}
...
基于
  • https://stackoverflow.com/a/16612739/5205022
  • https://stackoverflow.com/a/28086797/5205022
  • 关于scala - 使用 future 时程序不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62884361/

    相关文章:

    scala - 为什么 Scala for comprehension 按顺序运行 Future 函数?

    scala - 找不到用于测试的现有数据 Scala Specs2

    C fscanf 读取方括号之间的内容

    file - 如何获取 Intellij 工作区位置 URI

    c++ - 在多线程上下文中安全使用映射中的引用

    java - synchronized statements java——它们相对于非同步代码究竟做了什么?

    Scala - 增加序列的前缀

    scala - 登录 Scala : what to use when writing a library

    javascript - 如何在 Scalajs 项目中使用 Javascript 库

    file - 如何删除被锁定的文件?