Question

I'm trying to apply the future composition concept in my own application. According to the Akka documentation, you can do this (http://doc.akka.io/docs/akka/snapshot/java/futures.html):

final ExecutionContext ec = system.dispatcher();
//Some source generating a sequence of Future<Integer>:s
Iterable<Future<Integer>> listOfFutureInts = source;

// now we have a Future[Iterable[Integer]]
Future<Iterable<Integer>> futureListOfInts = sequence(listOfFutureInts, ec);

// Find the sum of the odd numbers
Future<Long> futureSum = futureListOfInts.map(
     new Mapper<Iterable<Integer>, Long>() {
          public Long apply(Iterable<Integer> ints) {
              long sum = 0;
              for (Integer i : ints)
                   sum += i;
              return sum;
         }
     }, ec);

futureSum.onSuccess(new PrintResult<Long>(), system.dispatcher());

Keep in mind, I'm developing with the Java version of Akka becasue I'm not familiar enough with Scala. This works fine when you want to compose futures that are succesful. Here, you're just aggregating the result of all the futures (ints) and summing them up and placing its result in another future that can be handled later. Now what happens if one of the futures possibly fails, i.e throws an exception. Naturally, you can handle failures with the 'onFailure' callback for any one specific future, but I haven't found a way to handle failures when composing futures.

What's the best way to do it? Should I be applying another concept entirely?

Thanks.

Was it helpful?

Solution

You're looking for recover and recoverWith as described here: http://doc.akka.io/docs/akka/2.3.2/java/futures.html#Exceptions

final ExecutionContext ec = system.dispatcher();

Future<Integer> future = future(new Callable<Integer>() {
  public Integer call() {
    return 1 / 0;
  }
}, ec).recover(new Recover<Integer>() {
  public Integer recover(Throwable problem) throws Throwable {
    if (problem instanceof ArithmeticException)
      return 0;
    else
      throw problem;
  }
}, ec);

future.onSuccess(new PrintResult<Integer>(), system.dispatcher());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top