Scala Future的地图是否会增加任何开销?

问题描述 投票:1回答:2

假设我有这样的函数:

import scala.concurrent._

def plus2Future(fut: Future[Int])
               (implicit ec: ExecutionContext): Future[Int] = fut.map(_ + 2)

现在我使用plus2Future创建一个新的Future

import import scala.concurrent.ExecutionContext.Implicits.global
val fut1 = Future { 0 }
val fut2 = plus2Future(fut1)

函数plus2现在总是在与fut1相同的线程上运行吗?我猜它没有。 在map中使用plus2Future是否会增加线程上下文切换的开销,创建一个新的Runnable等?

scala concurrency future
2个回答
2
投票

在plus2Future中使用map会增加线程上下文切换的开销,创建一个新的Runnable等吗?

map,关于Future的默认实现(通过DefaultPromise)是:

def map[S](f: T => S)(implicit executor: ExecutionContext): Future[S] = { // transform(f, identity)
  val p = Promise[S]()
  onComplete { v => p complete (v map f) }
  p.future
}

onComplete创建一个新的CallableRunnable并最终调用dispatchOrAddCallback

/** Tries to add the callback, if already completed, it dispatches the callback to be executed.
 *  Used by `onComplete()` to add callbacks to a promise and by `link()` to transfer callbacks
 *  to the root promise when linking two promises togehter.
 */
@tailrec
private def dispatchOrAddCallback(runnable: CallbackRunnable[T]): Unit = {
  getState match {
    case r: Try[_]          => runnable.executeWithValue(r.asInstanceOf[Try[T]])
    case _: DefaultPromise[_] => compressedRoot().dispatchOrAddCallback(runnable)
    case listeners: List[_] => if (updateState(listeners, runnable :: listeners)) () else dispatchOrAddCallback(runnable)
  }
}

其中调用底层执行上下文。这意味着由实施ExecutionContext来决定未来的运行方式和地点,因此无法给出“它在这里或那里运行”的确定性答案。我们可以看到有一个Promise和一个回调对象的分配。

总的来说,我不担心这个,除非我对代码进行基准测试并发现这是一个瓶颈。


1
投票

不,它不能(确定地)使用相同的线程(除非EC只有一个线程),因为在两行代码之间可以经过无限的时间量。

© www.soinside.com 2019 - 2024. All rights reserved.