Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created January 27, 2017 17:37
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/ea1aa7376d5f7f352d6dbe7df58a952f to your computer and use it in GitHub Desktop.
Save justinhj/ea1aa7376d5f7f352d6dbe7df58a952f to your computer and use it in GitHub Desktop.
Sample Scala code for creating a list of futures then executing them in parallel then shutting down when they are complete.
import java.util.concurrent.Executors
import scala.concurrent.{ExecutionContext, Future, Await}
import scala.concurrent.duration._
object conc1 {
val numThreads = 4
implicit val ec = new ExecutionContext {
val threadPool = Executors.newFixedThreadPool(numThreads)
def execute(runnable: Runnable) {
threadPool.submit(runnable)
}
def reportFailure(t: Throwable) {}
}
val r = scala.util.Random
def getThreadID = Thread.currentThread().getName()
def slowRandom(n: Int)(implicit ec: ExecutionContext): Future[Unit] = {
Future {
Thread.sleep(2000)
val a = r.nextInt(n)
println(s"produced random number $a on thread ${getThreadID}")
}
}
def main(args: Array[String]) : Unit ={
println("start")
val f = (1 to 20) map {
_ => slowRandom(1000)
}
val fs = Future.sequence(f)
println("waiting for futures")
Await.result(fs, 20 seconds)
ec.threadPool.shutdown()
println("end")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment