Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Let's compare Future.recover and Future.andThen
- // Try to answer these questions yourself:
- // 1. what is the expected type for each future?
- // 2. how many "Future1 started" lines expected in stdout?
- // 3. both PartialFunctions are not exhausive; what happens if it doesn't match the case?
- import java.time.LocalDateTime
- import scala.concurrent.ExecutionContext.Implicits.global
- import scala.concurrent.Future
- import scala.io.StdIn
- import scala.language.postfixOps
- import scala.util.Success
- object Main extends App {
- def print(x: Any): Unit = {Thread.sleep(50); println(s"${LocalDateTime.now()}: $x")}
- def f1 = Future {
- print("Future1 started")
- Thread.sleep(5000)
- print("Future1 finished")
- 5 / 2
- }
- val recoveredFuture: Future[AnyVal] = f1.recover { // AnyVal is common type for (Int, Long)
- case ex: ArithmeticException => println(s"Divide by 0 exception: $ex"); Long.MaxValue
- }
- val sideEffectFuture: Future[Int] = f1.andThen {
- case Success(x) => println(s"Result is $x")
- }
- print("Press ENTER to finish")
- StdIn.readLine()
- print(s"Results: $recoveredFuture; $sideEffectFuture")
- }
- // 1. Interrupted futures:
- // 2018-08-19T18:12:55.976: Future1 started
- // 2018-08-19T18:12:55.983: Future1 started
- // 2018-08-19T18:12:55.984: Press ENTER to finish
- //
- // 2018-08-19T18:12:57.250: Results: Future(<not completed>); Future(<not completed>)
- // 2. Successful execution:
- // 2018-08-19T18:13:07.345: Press ENTER to finish
- // 2018-08-19T18:13:07.345: Future1 started
- // 2018-08-19T18:13:07.345: Future1 started
- // 2018-08-19T18:13:12.400: Future1 finished
- // 2018-08-19T18:13:12.404: Future1 finished
- // Result is 2
- // 2018-08-19T18:13:13.328: Results: Future(Success(2)); Future(Success(2))
- // 3. Failed execution:
- 5 / 0
- // 2018-08-19T18:13:29.086: Future1 started
- // 2018-08-19T18:13:29.086: Future1 started
- // 2018-08-19T18:13:29.086: Press ENTER to finish
- // 2018-08-19T18:13:34.140: Future1 finished
- // 2018-08-19T18:13:34.140: Future1 finished
- // Divide by 0 exception: java.lang.ArithmeticException: / by zero
- //
- // 2018-08-19T18:13:36.240: Results: Future(Success(9223372036854775807)); Future(Failure(java.lang.ArithmeticException: / by zero))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement