Skip to content

Instantly share code, notes, and snippets.

@kovacshuni
Created April 1, 2022 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kovacshuni/9bc7f30b886f5a7feb287659f29e7e25 to your computer and use it in GitHub Desktop.
Save kovacshuni/9bc7f30b886f5a7feb287659f29e7e25 to your computer and use it in GitHub Desktop.
concurrent-futures-in-for-comprehensions
package com.hiya.h4b.cpas.futuretest
import akka.actor.ActorSystem
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
object FutureTestApp extends App {
private val sys = ActorSystem.apply("future-test-app")
implicit private val ec = sys.dispatcher
val t1 = System.currentTimeMillis()
val joinedFuture = for {
_ <- Future(Thread.sleep(5000))
_ <- Future(Thread.sleep(5000))
} yield ()
Await.ready(joinedFuture, 15 seconds)
val t2 = System.currentTimeMillis()
println(s"Waited ${t2 - t1}ms")
val f1 = Future(Thread.sleep(5000))
val f2 = Future(Thread.sleep(5000))
val joinedFuture2 = for {
_ <- f1
_ <- f2
} yield ()
Await.ready(joinedFuture2, 15 seconds)
val t3 = System.currentTimeMillis()
println(s"Waited ${t3 - t2}ms")
Await.ready(sys.terminate(), 10 seconds)
println(s"Shut down")
}
/* output:
[info] Waited 10008ms
[info] Waited 5009ms
[info] Shut down
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment