Skip to content

Instantly share code, notes, and snippets.

@akkomar
Created October 17, 2013 23:27
Show Gist options
  • Save akkomar/7034107 to your computer and use it in GitHub Desktop.
Save akkomar/7034107 to your computer and use it in GitHub Desktop.
Binary tree concurrent map
import java.util.concurrent._
import scala.{Option, Some, None}
case class Node[T](val v: T, l: Option[Node[T]], r: Option[Node[T]]) {
def map[R](f: T => R): Node[R] = {
new Node(f(v), l.map(n => n.map(f)), r.map(n => n.map(f)))
}
def mapConcurrently[R](f: T => R): Node[R] = {
val poolSize = Runtime.getRuntime.availableProcessors()
val pool: ExecutorService = Executors.newFixedThreadPool(poolSize + 1)
val result = mapWithPool(f, pool)
println(pool)
result
}
private def mapWithPool[R](f: T => R, pool: ExecutorService): Node[R] = {
val futureV = pool.submit(new Callable[R] {
def call(): R = f(v)
})
val left = l.map(n => n.mapWithPool(f, pool))
val right = r.map(n => n.mapWithPool(f, pool))
new Node(futureV.get(), left, right)
}
override def toString = "(" + v + " " + l.getOrElse(".") + " " + r.getOrElse(".") + ")"
}
object Node {
def apply[T](v: T): Node[T] = new Node(v, None, None)
def apply[T](v: T, l: Node[T], r: Node[T]): Node[T] = new Node(v, Some(l), Some(r))
}
val tree = Node(1,
Node(3, Node(4, Node(6), Node(7)), Node(5)), Node(2))
def longOp(i: Int): Int = {
Thread.sleep(1000)
i * 2
}
val cS = System.currentTimeMillis()
val newTree = tree.mapConcurrently(longOp(_))
println("Concurrent duration: " + (System.currentTimeMillis() - cS))
val sS = System.currentTimeMillis()
val newTree2 = tree.map(longOp(_))
println("Single thread duration: " + (System.currentTimeMillis() - sS))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment