How do I properly fire up a temporary actor in Akka?

akka

Solution

It sounds like you need to use a future. As far as I understand, Akka futures take care of actor creation & disposal for you; if you `flatMap` several futures together you'll notice that some execute within the same actor, while for others a new one is created. To shamelessly paraphrase the documentation:

import akka.japi.Function;
import java.util.concurrent.Callable;
import akka.dispatch.Futures;
import akka.dispatch.OnComplete;

Future<String> f = Futures.future(new Callable<String>() {
  public String call() {
    return "Hello" + "World";
  }
}, system.dispatcher()).andThen(new OnComplete<String>() {
    public void onComplete(Throwable err, String result) {
        // do something with the err and/or result
    }
   });
});

I guess something like the above might suffice? Check out the doc for more examples...

@viktor-clang might know otherwise, but I don't think you should be particularly worried about the number of actors spawned in the general case; they're much cheaper to create than OS threads.

Problem

I am building something similar (but not identical) to the ask pattern in Akka, where I need to instantiate a temporary actor that handled a single message and then kills itself. I've implemented the basic workflow using actorOf() once per request, but this doesn't feel quite right, as it will register a new actor at a new path each time. What is the proper way of doing this?

Original source