Execution context without daemon threads for futur

2019-01-27 02:26发布

问题:

I am having trouble with the JVM immediately exiting using various new applications I wrote which spawn threads through the Scala 2.10 Futures + Promises framework.

It seems that at least with the default execution context, even if I'm using blocking, e.g.

future { blocking { /* work */ }}

no non-daemon thread is launched, and therefore the JVM thinks it can immediately quit.

A stupid work around is to launch a dummy Thread instance which is just waiting, but then I also need to make sure that this thread stops when the processes are done.

So how to I enforce them to run on non-daemon threads?

回答1:

In looking at the default ExecutionContext attached to ExecutionContext.global, it's of the fork join variety and the Threadfactory it uses sets the threads to daemon. If you want to work around this, you could use a different ExecutionContext, one you set up yourself. If you still want the FJP variety (and you probably do as it scales the best), you should be able to look at what they are doing in ExecutionContextImpl via this link and create something similar. Or just use a cached thread pool via Executors.newCachedThreadPool as that won't shut down immediately before your futures complete.



回答2:

spawn processes

If this means processes and not just tasks, then scala.sys.process spawns non-daemon threads to run OS processes.

Otherwise, if you're creating a bunch of tasks, this is what Future.sequence helps with. Then just Await ready (Future sequence List(futures)) on the main thread.