假设我有这样的函数:
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
等?
在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
和一个回调对象的分配。
总的来说,我不担心这个,除非我对代码进行基准测试并发现这是一个瓶颈。
不,它不能(确定地)使用相同的线程(除非EC只有一个线程),因为在两行代码之间可以经过无限的时间量。