Skip to content

Instantly share code, notes, and snippets.

@gustavoamigo
Last active January 2, 2017 23:07
Show Gist options
  • Save gustavoamigo/9976bbab6f419ed3ae28c8c888037c85 to your computer and use it in GitHub Desktop.
Save gustavoamigo/9976bbab6f419ed3ae28c8c888037c85 to your computer and use it in GitHub Desktop.
Example of using explicit execution contexts with Scala Futures to isolate blocking IO.
import java.util.concurrent._
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}
object FixedThreadPool {
def apply(nThreads: Int, name: String, daemon: Boolean = true): ThreadPoolExecutor =
new ThreadPoolExecutor(nThreads,nThreads,0L,TimeUnit.MILLISECONDS,new SynchronousQueue[Runnable],new NamedThreadFactory(name, daemon))
}
class NamedThreadFactory(val name: String, daemon: Boolean, suppressExceptions: Boolean = false)
extends ThreadFactory {
private var counter = 0
def newThread(r: Runnable) = this.synchronized {
val thread = new Thread(r, name + "-" + counter) {
override def run() {
try {
r.run()
} catch {
case e: Exception =>
if (!suppressExceptions) throw e
}
}
}
counter += 1
if (daemon)
thread.setDaemon(true)
thread
}
}
object ScalaFuture extends App {
def printCurrentThread(txt: String) = println(s"Running $txt at ${Thread.currentThread.getName}")
def sleep(second:Long) = Thread.sleep(second * 1000)
val blockingEC = ExecutionContext
.fromExecutor(FixedThreadPool(10, "blocking-io"))
val nonBlockingEC = ExecutionContext
.fromExecutor(FixedThreadPool(10, "non-blocking-io"))
val myFuture1 = Future {
sleep(1)
printCurrentThread("myFuture1")
}(nonBlockingEC)
val myFuture2 = myFuture1.map{_=> sleep(1); printCurrentThread("myFuture2"); ()}(blockingEC)
Await.result(myFuture2, Duration.Inf)
/* Result
Running myFuture1 at non-blocking-io-0
Running myFuture2 at blocking-io-0
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment