Futures and Promises in Scala

 Futures and Promises in Scala


Futures and promises are a way to perform asynchronous computations in Scala. A future represents a computation that may not have finished yet, while a promise is a way to produce a value that may not be available yet. Here's an example of using futures and promises to perform an expensive computation:

scss


import scala.concurrent.Future

import scala.concurrent.ExecutionContext.Implicits.global


def computeResult(): Future[Int] = {

  val promise = scala.concurrent.Promise[Int]()

  Future {

    // Perform expensive computation here

    Thread.sleep(1000)

    promise.success(42)

  }

  promise.future

}


val futureResult = computeResult()

println("Waiting for result...")

val result = Await.result(futureResult, Duration.Inf)

println(s"The result is $result.")

In this example, a computeResult function is defined that returns a Future[Int]. Inside the function, a promise is created to produce the result, and an expensive computation is performed inside a Future block. Once the computation is finished, the promise is fulfilled with the result. Finally, the futureResult value is obtained by calling the computeResult function, and the result is obtained by blocking until the future completes using the Await.result method.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...