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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

I just found this other working Akka Future example in the discussion group:

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

object HelloWorldFuture {
  def main(args: Array[String]) {
    val pool = Executors.newCachedThreadPool()
    implicit val ec = ExecutionContext.fromExecutorService(pool)
    val future = Future {
      "Hello" + "World"
    }
    val result = Await.result(future, 1 second)
    println(result)
    pool.shutdown()
  }
}

Here's a link to that discussion and the person named "Mic" who solved this problem in a slightly different way.

Permalink

Below is how to do it. Thanks for reporting. We will improve docs.

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

scala> import akka.dispatch._
import akka.dispatch._

scala> implicit val system = ActorSystem("MySys")
system: akka.actor.ActorSystem = akka://MySys

scala> val future = Future {1 + 1}
future: akka.dispatch.Future[Int] = akka.dispatch.DefaultPromise@473a3bc4

scala> val result = Await.result(future, 1 second)
result: Int = 2

Thanks for your reply. I kept missing the "implicit" keyword when creating the ActorSystem. I also had to import "akka.util.duration._", and this now works great:

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)

}

Thanks again!

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.