Skip to content

Instantly share code, notes, and snippets.

@alaz
Forked from jessitron/gist:8777503
Last active April 4, 2016 09:39
Show Gist options
  • Save alaz/30632a3d9dfd385c82e4dda77bf1f351 to your computer and use it in GitHub Desktop.
Save alaz/30632a3d9dfd385c82e4dda77bf1f351 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
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)
ct
} (des)
def pauseThread(sec:Int) = future {
println("Sleeping on thread " + ct)
blocking {Thread.sleep(sec * 1000) }
println("Freeing thread " + ct)
ct
} (des)
val futures = 0 to (n + 1) map { _ => hogThread(4) }
val allThreads = Future.fold(futures)(Set.empty[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.empty[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