Han*_*Sun 2 concurrency scala future akka
在模块的源代码中Future,我看到了这样的定义onComplete:
/** When this future is completed, either through an exception, or a value,
* apply the provided function.
*
* If the future has already been completed,
* this will either be applied immediately or be scheduled asynchronously.
*
* $multipleCallbacks
* $callbackInContext
*/
def onComplete[U](@deprecatedName('func) f: Try[T] => U)(implicit executor: ExecutionContext): Unit
Run Code Online (Sandbox Code Playgroud)
这看起来很奇怪,因为它没有函数体(没有实现).那么为什么要这么做onComplete呢?它是用Java实现的吗?我怎样才能找到真正的实现代码?
深入挖掘一下.你通常如何创建一个Future?一种方法是Future.apply.
def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = impl.Future(body)
Run Code Online (Sandbox Code Playgroud)
impl.Future.apply创造一个PromiseCompletingRunnable持有一个Promise.
def apply[T](body: =>T)(implicit executor: ExecutionContext): scala.concurrent.Future[T] = {
val runnable = new PromiseCompletingRunnable(body)
executor.prepare.execute(runnable)
runnable.promise.future
}
Run Code Online (Sandbox Code Playgroud)
特别是,它会创建一个Promise.DefaultPromise,它实现onComplete.在同一个源文件中,您还可以看到默认Promise实现也是一个Future.当我们打电话时promise.future,它只是将自己作为一个回归Future.所以它就在标准库中.
如果您要在Scala存储库中搜索"def onComplete",您只会获得一些结果,因此很容易找到.