代码之家  ›  专栏  ›  技术社区  ›  user79074

如何立即执行未来

  •  0
  • user79074  · 技术社区  · 11 月前

    假设我的未来定义如下

    val fut = Future {
      println("Doing some work")
      Thread.sleep(5000)
      println("Work done")
    }
    

    我稍后会访问这个未来,但希望在启动时执行它,而不是在我引用fut时执行

    我在某个地方读到,通过执行以下操作可以立即执行:

    scala.concurrent.ExecutionContext.Implicits.global.execute(fut)
    

    然而,这不会编译,因为execute只需要一个Runnable。 有没有一种方法可以在不同的线程中立即执行这个未来?

    1 回复  |  直到 11 月前
        1
  •  0
  •   sarveshseri    11 月前

    Scala Future s使用创建 Future.apply 被热切地执行。

    对于非急切执行,您必须定义自己的类来间接创建 未来 使用 Promise .

    import scala.concurrent.{Future, Promise}
    import scala.util.{Failure, Success, Try}
    
    class NonEagerFuture[A](computation: => A) extends Runnable {
      private val promise = Promise[A]
    
      override def run(): Unit = {
        Try(computation) match {
          case Success(result)    => promise.success(result)
          case Failure(exception) => promise.failure(exception)
        }
      }
    
      def isFutureCompleted(): Boolean =
        promise.isCompleted
    
      def getResult(): A =
        if (!promise.isCompleted) {
          throw new IllegalStateException("Future is not completed yet")
        } else {
          promise.future.value.get.get
        }
    
      def getScalaFuture(): Future[A] =
        promise.future
    
    }
    

    它可以如下使用,

    println("creating the future")
    
    val nonEagerFuture = new NonEagerFuture({
      println("Doing some work")
      Thread.sleep(5000)
      println("Work done")
      println("returning 5 as result")
      5
    })
    
    println("running for the future")
    scala.concurrent.ExecutionContext.Implicits.global.execute(nonEagerFuture)
    
    // can also get the internal scala future and use it
    // this scala future will not have the eager problem 
    println("get the scala future") 
    val scalaFuture = nonEagerFuture.getScalaFuture()
    println("printing scalaFuture" + scalaFuture)
    
    // or block for completion using isFutureCompleted
    println("checking for the future")
    while (!nonEagerFuture.isFutureCompleted()) {
      Thread.sleep(1000)
      println("Checking completed: " + nonEagerFuture.isFutureCompleted())
    }
    
    println("getting result for the future")
    println("Result: " + nonEagerFuture.getResult())
    
    推荐文章