Program not terminating when using Futures

前端 未结 1 1503
梦如初夏
梦如初夏 2021-01-19 21:29

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

相关标签:
1条回答
  • 2021-01-19 22:11

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

    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

    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))
    

    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)
    }
    ...
    

    Based on

    • https://stackoverflow.com/a/16612739/5205022
    • https://stackoverflow.com/a/28086797/5205022
    0 讨论(0)
提交回复
热议问题