Created
January 27, 2017 17:37
-
-
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.
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 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