Skip to content

Instantly share code, notes, and snippets.

@earldouglas
Created November 25, 2011 07:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earldouglas/1392983 to your computer and use it in GitHub Desktop.
Save earldouglas/1392983 to your computer and use it in GitHub Desktop.
package await
import java.util.concurrent.Callable
import java.util.concurrent.Executors
object BlockingDemo extends App {
val execSvc = Executors.newSingleThreadExecutor()
val worker = new MeaningOfLife()
var future = execSvc.submit(worker)
println("Thinking...")
println("The meaning of life is " + future.get())
println("All done!")
execSvc.shutdown()
}
package await
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import scala.util.continuations._
import await.Await.pimpWorker
object NonblockingDemo extends App {
implicit val execSvc = Executors.newSingleThreadExecutor()
val worker = new MeaningOfLife()
println("Thinking...")
reset(println("The meaning of life is " + worker.await()))
println("All done!")
execSvc.shutdown()
}
object Await {
implicit def pimpWorker[A](callable: Callable[A])(implicit execSvc: ExecutorService): Await[A] = new Await(callable, execSvc)
}
class Await[A](callable: Callable[A], execSvc: ExecutorService) {
def await(): A @suspendable = shift { k: (A => Unit) =>
val worker = new AwaitWorker(callable, k)
execSvc.submit(worker)
}
}
class AwaitWorker[A](callable: Callable[A], k: A => Unit) extends Callable[Unit] {
def call(): Unit = k(callable.call())
}
package await
import java.util.concurrent.Callable
class MeaningOfLife extends Callable[Int] {
def call(): Int = {
Thread.sleep(5000)
42
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment