Skip to content

Instantly share code, notes, and snippets.

@tstone
Last active January 3, 2016 10:29
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 tstone/8449893 to your computer and use it in GitHub Desktop.
Save tstone/8449893 to your computer and use it in GitHub Desktop.
Scala Futures + For Comprehension/Seq's
// DEMO CODE
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def time[A](label: String, block: => Future[A]) = {
val t0 = System.nanoTime()
block.onComplete {
case _ => {
val t1 = System.nanoTime()
println(s"[$label] elapsed time: " + ((t1 - t0) / 1000000000) + "s")
}
}
}
def test1 = {
for {
f1Result <- Future { Thread.sleep(3000); 1 }
f2Result <- Future { Thread.sleep(3000); 2 }
f3Result <- Future { Thread.sleep(3000); 3 }
} yield (f1Result, f2Result, f3Result)
}
def test2 = {
val fut1 = Future { Thread.sleep(3000); 1 }
val fut2 = Future { Thread.sleep(3000); 2 }
val fut3 = Future { Thread.sleep(3000); 3 }
for {
f1Result <- fut1
f2Result <- fut2
f3Result <- fut3
} yield (f1Result, f2Result, f3Result)
}
def test3 = {
// Seq[Future] => Future[Seq]
Future.sequence(Seq(
Future { Thread.sleep(3000); 1 },
Future { Thread.sleep(3000); 2 },
Future { Thread.sleep(3000); 3 }
))
}
time("test1", test1)
time("test2", test2)
time("test3", test3)
// OUTPUT:
// [test2] elapsed time: 3s
// [test3] elapsed time: 3s
// [test1] elapsed time: 9s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment