Skip to content

Instantly share code, notes, and snippets.

@tifletcher
Last active May 17, 2024 04:52
Show Gist options
  • Save tifletcher/91e928e3dab80640a88a750637dd7547 to your computer and use it in GitHub Desktop.
Save tifletcher/91e928e3dab80640a88a750637dd7547 to your computer and use it in GitHub Desktop.
parallel and sequential futures
import scala.concurrent.Future
implicit val ec = scala.concurrent.ExecutionContext.global
def future(name: String): Future[String] = {
println(s"constructing $name")
Future {
Thread.sleep(1000)
println(s"resolved $name")
name
}
}
implicit class Resultable(f: Future[Seq[String]]) {
def printresult(which: String): Unit = {
f.foreach { res =>
println(s"$which completed: [${res.mkString(", ")}]")
}
}
}
// ------------------------------------ BEGIN
println("1 - SEQUENTIAL: for comprehension:")
(for {
a <- future("1 - a")
b <- future("1 - b")
} yield Seq(a, b)).printresult("sequential for")
println("2 - PARALLEL: construct upfront and consume sequentially with for comprehension")
val a = future("2 - a")
val b = future("2 - b")
(for {
aa <- a
bb <- b
} yield Seq(aa, bb)).printresult("parallel for")
println("3 - PARALLEL from sequence:")
Future.sequence(Seq(future("3 - a"), future("3 - b"))).printresult("parallel sequence")
println("4 - SEQUENTIAL from sequence:")
def chain[T](futureLambdas: Seq[() => Future[T]]): Future[Seq[T]] = {
def chain(futureLambdas: List[() => Future[T]], acc: List[T]): Future[List[T]] = futureLambdas match {
case Nil => Future.successful(acc)
case head::tail => head.apply().flatMap { v =>
chain(tail, acc :+ v)
}
}
chain(futureLambdas.toList, Nil)
}
val fs = Seq(
() => future("4 - a"),
() => future("4 - b")
)
chain(fs).printresult("sequential sequence")
println("sleeping for 4 seconds")
Thread.sleep(4000)
println("goodbye")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment