Run one task, but block

The following example demonstrates how to create a Future and then block the sequence of execution in order to wait for its result. Creating Futures is trivial. You just need to pass it to the code that you want. The following example performs 2+2 in the future and then returns the results:

package com.chapter3.ScalaFP
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

object RunOneTaskbutBlock {
def main(args: Array[String]) {
// Getting the current time in Milliseconds
implicit val baseTime = System.currentTimeMillis
// Future creation
val testFuture = Future {
Thread.sleep(300)
2 + 2
}
// this is the blocking part
val finalOutput = Await.result(testFuture, 2 second)
println(finalOutput)
}
}

The Await.result method waits up to 2 seconds till the Future returns the result; if it doesn't return the result within 2 seconds, it throws the following exception you might want to handle or catch:

java.util.concurrent.TimeoutException

It's time to wrap up this chapter. However, I would like to take the chance to discuss an important view of mine about functional programming with Scala and object mutability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.180.145