Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.