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?

emchristiansen
  • 3,550
  • 3
  • 26
  • 40
0__
  • 66,707
  • 21
  • 171
  • 266
  • 1
    What `ExecutionContext` are you using? Are you creating it yourself or are you getting it from `ExecutionContext.global`? – cmbaxter May 17 '13 at 15:18
  • I think it happens both with `global` and instantiating a single threaded one, that's basically the two scenarios I have. – 0__ May 17 '13 at 20:12

2 Answers2

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.

cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • `private[scala]`, grmpff. But anyway thanks for the link, and confirming that they set daemon to true (without any possibility of configuring that, damn...) – 0__ May 17 '13 at 20:15
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.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • Sorry for the wrong wording. No, I run computations within my process. So, threads technically. – 0__ May 17 '13 at 20:11