Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Last active July 30, 2018 11:27
Show Gist options
  • Save petitviolet/d5ed010ce4ce12bc250b3f259c97ff02 to your computer and use it in GitHub Desktop.
Save petitviolet/d5ed010ce4ce12bc250b3f259c97ff02 to your computer and use it in GitHub Desktop.
[Scala]Pay attention to the timing to call `Future.apply`.

what is this?

scala.concurrent.Future let asynchronous programming easily. We can process a code block asynchronously by providing it to Future.apply. The timing to start processing is just Future.apply invoked. (also, needs a idling thread.) Therefore, pay attention to the timing to call it.

not in parallel

for {
    a <- Future { sleep(100); println(100); 100 }
    b <- Future { sleep(50); println(50); 50 }
} yield a + b

100
50

in parallel

val aF = Future { sleep(100); println(100); 100 }
val bF = Future { sleep(50); println(50); 50 }

for {
    a <- aF
    b <- bF
} yield a + b

50
100

or,

for {
    (a, b) <- Future { sleep(100); println(100); 100 } zip Future { sleep(50); println(50); 50 }
} yield a + b

50
100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment