Execution context without daemon threads for futures
Asked Answered
J

2

3

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?

Jedlicka answered 17/5, 2013 at 15:14 Comment(2)
What ExecutionContext are you using? Are you creating it yourself or are you getting it from ExecutionContext.global?Beebe
I think it happens both with global and instantiating a single threaded one, that's basically the two scenarios I have.Jedlicka
B
4

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.

Beebe answered 17/5, 2013 at 15:26 Comment(1)
private[scala], grmpff. But anyway thanks for the link, and confirming that they set daemon to true (without any possibility of configuring that, damn...)Jedlicka
P
1

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.

Pitta answered 17/5, 2013 at 18:31 Comment(1)
Sorry for the wrong wording. No, I run computations within my process. So, threads technically.Jedlicka

© 2022 - 2024 — McMap. All rights reserved.