Wednesday, 4 September 2013

Thread affinity: small Scala code snippet

This is a piece of code that allows you to bind a task, via its task id, to a thread.
import scala.actors.threadpool.Executors
import scala.collection.concurrent.TrieMap
import scala.actors.threadpool.ExecutorService

object ThreadAffinity {
  val es = {
    val nbCores = Runtime.getRuntime.availableProcessors
    val execList = for(i <- 0 until nbCores) yield Executors.newSingleThreadExecutor
    val execStr = for(x <- Stream.continually(); y <- execList) yield y
    execStr.iterator
  }
  
  val idExecMap = TrieMap[Int, ExecutorService]()
  
  def exec(taskId: Int, task: Runnable) = idExecMap.getOrElseUpdate(taskId, es.next).execute(task)
}
I like the use of the "continually stream" that iterates over the list of pre-created threads. I also like the very handy getOrElseUpdate from TrieMap

No comments:

Blog Archive