Create a gist now

Instantly share code, notes, and snippets.

The magic of blocking { ... } in Scala's global ExecutionContext: it leads to the creation of more threads, so the CPUs don't get bored
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