gpt4 book ai didi

scala - 使用 Scala future 时,是否会将具有相同执行上下文的链式回调优化为同步调用?

转载 作者:行者123 更新时间:2023-12-03 20:51:26 26 4
gpt4 key购买 nike

Scala 2.10 中的新 Future 为每个异步调用操作的操作(包括 mapfilter 等)使用执行上下文。这是否意味着每个操作将始终通过执行上下文单独调用,或者在链接多个转换/过滤器​​时是否有可能优化此步骤,每个转换/过滤器​​都使用相同的执行上下文?

IE。如果做 f.map(...).filter(...).map(...) ,都具有相同的执行上下文,将调用 execute()一次(因为它足够聪明,可以从上面组合一个同步函数),还是三次?

如果 Scala future 不进行上述优化,是否有替代框架更适合执行上述操作的长链组合?

最佳答案

我无法提供任何指向文档的链接,这些链接将清楚地说明将发生什么,但我们可以进行一个简单的实验来回答您的问题。
只需打开 Scala REPL 并粘贴以下代码:

import java.util.concurrent.Executors
import scala.concurrent._

implicit val ec = new ExecutionContext {
val threadPool = Executors.newFixedThreadPool(1000);

def execute(runnable: Runnable) {
threadPool.submit(runnable)
println("execute!")
}

def reportFailure(t: Throwable) {}
}

future { 1 } map(_ + 1) filter (_ > 0) map (_ + 2)
它会打印:
scala> future { 1 } map(_ + 1) filter (_ > 0) map (_ + 2)
执行!
执行!
执行!
执行!
res0: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@7ef3de76
因此,您正在执行的每个操作都会调用 execute (并且您可以在文档中查看每个函数,如 map 或 filter 都将 ExecutionContext 作为隐式参数: http://www.scala-lang.org/api/2.10.6/#scala.concurrent.Future )
如果您正在寻找替代框架,您应该查看 scalaz Futures。我对他们没有经验,但他们似乎是你正在寻找的。检查此线程: 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.

关于scala - 使用 Scala future 时,是否会将具有相同执行上下文的链式回调优化为同步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com