使用期货时程序未终止 [英] Program not terminating when using Futures

查看:81
本文介绍了使用期货时程序未终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试同时在目录中的每个文件上运行一个函数。可悲的是,每当我使用期货时,我的程序都不想终止(永远运行)。我试过使用 Await.result()得到相同的结果:/

I'm trying to concurrently run a function on each file in a directory. Sadly whenever I use Futures my program doesn't want to terminate (runs forever). I have tried using Await.result() with the same result :/

在运行代码时,它执行得很好,甚至完成?被打印,然后挂起...

When running the code it executes fine, even "finish?" gets printed and then it hangs...

这里是我的代码。 (我是Scala的新手)

Heres my code. (I'm new to 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 会创建非守护线程

Executors.newFixedThreadPool uses under the hood defaultThreadFactory which creates non-daemon thread


返回用于创建新线程的默认线程工厂。
工厂在同一
ThreadGroup中创建执行程序使用的所有新线程...每个新线程均作为非守护程序线程创建

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 创建守护程序线程

Because these are non-daemon threads the program does not terminate. On the other hand, for example, scala.concurrent.ExecutionContext.Implicits.global creates daemon threads

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 ,因此以下程序将在结尾处终止

where we note daemonic = true, so the following program would terminate at the end

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

这篇关于使用期货时程序未终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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