Write an example of future using Await.ready and Await.result

admin

7/14/2024
All Articles

#Write an example of future using Await.ready Await.result

Write an example of future using Await.ready and Await.result

Write an example of future using Await.ready and Await.result

Both are blocking for at most the given Duration. However, Await.result tries to return the future result right away and throws an exception if the future failed while Await.ready returns the completed future from which the result (Success or Failure) can safely be extracted via the value property.
They both block until the future completes, the difference is just their return type.
The difference is useful when your Future throws exceptions:

 

import scala.concurrent.Future
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
import scala.concurrent.duration._
import scala.concurrent.Await
object FutureDemo{
 def main(args: Array[String]): Unit = {

      val future = Future { 10 }
       val future2 = Future { 11 }
       val lst= Future {List(1,2,3)}

    try {
      val result = Await.result(future, 2.seconds)
      val result1 = Await.result(future2, 2.seconds)
      val result3 =Await.result(lst,2.seconds)
      println(result+result1)
      print(result3.map(i=>i*2))
    } catch {
      case e: TimeoutException => println("The operation timed out")
    }

 }
}