Bober02 Bober02 - 2 months ago 11
Scala Question

Scala - futures and concurrency

I am trying to understand Scala futures coming from Java background: I understand you can write:

val f = Future { ... }


then I have two questions:


  1. How is this future scheduled? Automatically?

  2. What scheduler will it use? In Java you would use an executor that could be a thread pool etc.



Furthermore, how can I achieve a
scheduledFuture
, the one that executes after a specific time delay? Thanks

Answer

The Future { ... } block is syntactic sugar for a call to Future.apply (as I'm sure you know Maciej), passing in the block of code as the first argument.

Looking at the docs for this method, you can see that it takes an implicit ExecutionContext - and it is this context which determines how it will be executed. Thus to answer your second question, the future will be executed by whichever ExecutionContext is in the implicit scope (and of course if this is ambiguous, it's a compile-time error).

In many case this will be the one from import ExecutionContext.Implicits.global, which can be tweaked by system properties but by default uses a ThreadPoolExecutor with one thread per processor core.

The scheduling however is a different matter. For some use-cases you could provide your own ExecutionContext which always applied the same delay before execution. But if you want the delay to be controllable from the call site, then of course you can't use Future.apply as there are no parameters to communicate how this should be scheduled. I would suggest submitting tasks directly to a scheduled executor in this case.