Klangism

Things that were important enough at the time when they were written.

Viktor Klang is a legendary programmer, known from places like the Internet. Consider following him on Twitter.

Nov 29

The Future is dead?

No! Long live the Future!

Something that’s new in Akka 1.0-RC1 is the possibility to add hooks that are executed when a Future is completed.

Behold!

Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import akka.actor._
import akka.actor._

scala> import akka.actor.Actor._
import akka.actor.Actor._

scala> val actor = actorOf( new Actor {
  def receive = {
    case “foo” => Thread.sleep(10000); /*Simulate blocking*/
                  self.reply(“bar”)
  }
}).start

scala> (actor.!!![String](“foo”)) onComplete {
  f => println(
         if (f.result.isDefined)
           “Got result: ” + f.result.get
         else
           “Got exception: ” + f.exception.get
       )
}

11:55:33.762 [akka:event-driven:dispatcher:global-3] DEBUG akka.dispatch.MonitorableThread - Created thread akka:event-driven:dispatcher:global-3
res8: akka.dispatch.Future[String] = akka.dispatch.DefaultCompletableFuture@422f3d17

scala> Got result: bar

This also enables non-busy-waiting Futures.awaitAll, Futures.awaitOne and Futures.awaitEither!

Happy hAkking!


  1. klangism posted this