Created
July 28, 2017 04:27
-
-
Save justinhj/e7d61f3ed968b50e9b568d55fd543047 to your computer and use it in GitHub Desktop.
Example of running futures in parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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