"when using scala futures, will chained callbacks with the same execution context be optimised into synchronous calls?" Code Answer


i cannot provide any link to documentation which will clearly state what will really happen, but we can conduct a simple experiment which will answer your question.

just open the scala repl and paste the following code:

import java.util.concurrent.executors
import scala.concurrent._

implicit val ec = new executioncontext {
    val threadpool = executors.newfixedthreadpool(1000);

    def execute(runnable: runnable) {

    def reportfailure(t: throwable) {}

future { 1 } map(_ + 1) filter (_ > 0) map (_ + 2) 

it will print:

scala> future { 1 } map(_ + 1) filter (_ > 0) map (_ + 2)
res0: scala.concurrent.future[int] = scala.concurrent.impl.promise$defaultpromise@7ef3de76

so execute is called for every single operation you are doing (and as you can check in the documentation each function like map or filter takes executioncontext as an implicit parameter: http://www.scala-lang.org/api/2.10.6/#scala.concurrent.future)

if you are looking for an alternative framework you should check scalaz futures. i have no experience with them, but they seems to be what you are looking for. check this thread: https://groups.google.com/forum/#!msg/scalaz/-puakif-g_4/7ydru5vifdqj

unlike the future implementation in scala 2.10, map and flatmap do not spawn new tasks and do not require an implicit executioncontext. instead, map and flatmap merely add to the current (trampolined) continuation that will be run by the 'current' thread, unless explicitly forked via future.fork or future.apply. this means that future achieves much better thread reuse than the 2.10 implementation and avoids needless thread pool submit cycles.

future also differs from the scala 2.10 future type in that it does not necessarily represent a running computation. instead, we reintroduce nondeterminism explicitly using the functions of the scalaz.nondeterminsm interface. this simplifies our implementation and makes code easier to reason about, since the order of effects and the points of nondeterminism are made fully explicit and do not depend on scala's evaluation order.

important note: future does not include any error handling and should generally only be used as a building block by library writers who want to build on future's capabilities but wish to design their own error handling strategy. see scalaz.concurrent.task for a type that extends future with proper error handling -- it is merely a wrapper for future[either[throwable,a]] with a number of additional convenience functions.

By holygeek on March 2 2022

Answers related to “when using scala futures, will chained callbacks with the same execution context be optimised into synchronous calls?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.