Scala: A simple Akka “Futures” example

Akka Futures FAQ: Can you share a simple example that shows how to use an Akka Future?

Sure. To fix a problem in my Sarah application I needed to be able to run some operations concurrently. After digging through the Akka Actors documentation I found that you can run simple operations as a Future, almost as easily as this:

val future = Future {
  1 + 1
}
val result = Await.result(future, 1 second)

That simple code calculates "1 + 1", and after it executes the variable result will have the value 2.

If you're not familiar with Akka Futures, here's a quick description from their documentation:

In Akka, a Future is a data structure used to retrieve the result of some concurrent operation. This operation is usually performed by an Actor or by the Dispatcher directly. This result can be accessed synchronously (blocking) or asynchronously (non-blocking).

Examples: Akka Future with (a) an ActorSystem or (b) a thread pool

I initially had some problems getting my Futures examples working, but thanks to Patrik Nordwall (see the Comments below), here's an example of how to use Futures with an Akka ActorSystem:

import akka.actor._
import akka.dispatch._
import akka.util.duration._

object Futures extends App {

  implicit val system = ActorSystem("FutureSystem")
  val future = Future {
    1 + 1
  }
  val result = Await.result(future, 1 second)
  println(result)

}

Here's a second example I was able to piece together earlier based on this thread in the Akka discussion group:

import akka.dispatch.{ Await, ExecutionContext, Future }
import akka.util.duration._
import java.util.concurrent.Executors

object Futures extends App {

  val pool = Executors.newCachedThreadPool()
  implicit val ec = ExecutionContext.fromExecutorService(pool)

  // note that the type is properly returned
  val future = Future {
    1 + 1  // you can return other data types, like "Hello world"
  }
  val result = Await.result(future, 1 second)
  println(result)

  pool.shutdown

}

Assuming you have sbt installed, you can save either of these examples in a file named Futures.scala in an empty directory, then create a build.sbt file like this (copied from this Akka page):

name := "Futures Test Project"
 
version := "1.0"
 
scalaVersion := "2.9.1"
 
resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
 
libraryDependencies += "com.typesafe.akka" % "akka-actor" % "2.0"

Then when you run your project with sbt like this:

$ sbt run

you should get the exciting output that one plus one is indeed two. (I encourage you to try other examples in the Future block to see how they work.)

Check it out

The Akka Actors library, and Futures examples in particular, make using concurrency so easy that it suddenly becomes very appealing, and I encourage you to check it out:

I hope these working examples, combined with the other Akka Futures documentation, will get you up and running very quickly.