Clarification needed about futures and promises in Scala

前端 未结 3 1862
一整个雨季
一整个雨季 2020-12-04 07:37

I am trying to get my head around Scala\'s promise and future constructs.

I\'ve been reading Futures and Promises in Scala Documentation and am a bit confused as I\'

3条回答
  •  甜味超标
    2020-12-04 08:05

    Note that under the hood Future is implemented in terms of Promise and this Promise is completed with the body you passed to your Future:

    def apply[T](body: =>T): Future[T] = impl.Future(body)  //here I have omitted the implicit ExecutorContext
    

    impl.Future is an implementation of Future trait:

    def apply[T](body: =>T)(implicit executor: ExecutionContext): scala.concurrent.Future[T] =
    {
      val runnable = new PromiseCompletingRunnable(body)
      executor.prepare.execute(runnable)
      runnable.promise.future
    }
    

    Where PromiseCompletingRunnable looks like this:

    class PromiseCompletingRunnable[T](body: => T) extends Runnable {
    val promise = new Promise.DefaultPromise[T]()
    
    override def run() = {
      promise complete {
        try Success(body) catch { case NonFatal(e) => Failure(e) }
      }
    } }
    

    So you see even though they are seperate concepts that you can make use of independently in reality you can't get Future without using Promise.

提交回复
热议问题