Created
November 25, 2011 07:16
-
-
Save earldouglas/1392983 to your computer and use it in GitHub Desktop.
Scala await implementation re: http://blog.ometer.com/2011/11/13/task-dispatch-and-nonblocking-io-in-scala/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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