Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created July 28, 2017 04:27
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 justinhj/e7d61f3ed968b50e9b568d55fd543047 to your computer and use it in GitHub Desktop.
Save justinhj/e7d61f3ed968b50e9b568d55fd543047 to your computer and use it in GitHub Desktop.
Example of running futures in parallel
import scala.concurrent.duration._
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, Future}
import scala.language.postfixOps
import scala.concurrent.ExecutionContext.Implicits.global
object ParallelFuture {
def printWithTimeAndThreadID(s : String): Unit = println(s"${System.currentTimeMillis()} thread id ${Thread.currentThread().getId} : $s")
// A simple example future which takes configurable time and returns the thread ID it ran on
// The label is so we can identify the job in the output ...
def timedFuture(finiteDuration: FiniteDuration, label: String): Future[Long] = Future {
if(label.startsWith("job 2")) throw new Exception("oh dead")
printWithTimeAndThreadID(s"starting $label")
Thread.sleep(finiteDuration.toMillis)
printWithTimeAndThreadID(s"completing $label")
Thread.currentThread().getId
}
def main(args: Array[String]): Unit = {
// This function shows how to run futures in parallel using Future.sequence
// which takes a List[Future[A]] and returns a Future[List[A]]
def threeAtOnce(a: Long) = Future.sequence((1 to 3).map {
n => timedFuture(5 seconds, s"job $n $a")
})
// Simple demo where we run the first job then run three jobs
// in parallel with the result
val exampleF = for (
a <- timedFuture(3 seconds, "first job");
b <- threeAtOnce(a)
) yield (a,b)
val runMe = exampleF
Await.ready(exampleF, 10 seconds)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment