Created
February 3, 2014 01:09
-
-
Save jessitron/8777503 to your computer and use it in GitHub Desktop.
The magic of blocking { ... } in Scala's global ExecutionContext: it leads to the creation of more threads, so the CPUs don't get bored
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
val des = scala.concurrent.ExecutionContext.global | |
import scala.concurrent._ | |
import duration._ | |
def ct = Thread.currentThread.getName | |
val n = Runtime.getRuntime.availableProcessors | |
def hogThread(sec:Int) = future { | |
println("Sleeping on thread " + ct) | |
Thread.sleep(sec * 1000) | |
println("Freeing thread " + ct) | |
} (des) | |
def pauseThread(sec:Int) = future { | |
println("Sleeping on thread " + ct) | |
blocking {Thread.sleep(sec * 1000) } | |
println("Freeing thread " + ct) | |
} (des) | |
val futures = 0 to (n + 1) map { _ => hogThread(4) } | |
val allThreads = Future.fold(futures)(Set[String]())( _ + _ )(des) // set of thread names | |
allThreads.onSuccess{ case s => println("Number of unique threads: " + s.size) }(des) | |
// 8 unique threads, because I have 8 CPUs | |
val futures = 0 to (n + 1) map { _ => pauseThread(4) } // uses blocking { ... } | |
val allThreads = Future.fold(futures)(Set[String]())( _ + _ )(des) // set of thread names | |
allThreads.onSuccess{ case s => println("Number of unique threads: " + s.size) }(des) | |
// 10 unique threads, because 0..(8+1) gives 10 numbers, so 10 Futures started |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on your code I created a version as specs2 test: https://github.com/AlexanderDaniel/scala-playground/blob/master/src/test/scala/lachdrache/futures/ExecutionContextSpec.scala