Search code examples
javaasynchronousakkaactorfuture

Implementing the Ask Pattern on the Recipient-Side in Akka-Java Land


Every Akka tutorial and its grandmother proudly displays snippets of code, like the one below, showing off how to perform an asynchronous, non-blocking ask via Akka Futures:

// Groovy pseudo code
class Fizz extends UntypedActor {
    ActorRef buzz

    Fizz(ActorRef buzz) {
        super()

        this.buzz = buzz
    }

    @Override
    void onReceive(Object message) {
        if(message instanceof DoSomething) {
            DoSomething ds = message as DoSomething
            Foo foo = doSomething(ds)
            Future<BuzzResult> buzzFut = buzz.ask(new ProcessResult(foo))

            buzzFut.onSuccess(new BuzzResultHandler(), system.dispatcher)
        }
    }

    Foo doSomething(DoSomething ds) { … }
}

But nowhere can I actually find a code snippet that shows how to service this ask on the other (recipient) side. Okay, so Fizz has asked Buzz with a ProcessResult message, and has set up an onSuccess handler to capture the result once Buzz sends it back. But how does Buzz actually send it back?!?

Buzz is an actor, and so it does all its messaging through onReceive:

class Buzz extends UntypedActor {
    @Override
    void onReceive(Object message) {
        if(message instanceof ProcessResult) {
            ProcessResult pr = message as ProcessResult

            BuzzResult br = BuzzResultFactory.createBuzzResult(pr)

            // Oh snap, I can’t send ‘br’ back to the Fizz’s BuzzResultHandler 
            // because I return void…
        }
    }
}

If onReceive returns void, how can it ever possibly return a result when asked something by Fizz (or any other actor)?!?

Of course I welcome and am enormously appreciative of any answers, even in Scala, but would ask for any code snippets to be in Java since Scala looks like hieroglyphics to me.


Solution

  • That's pretty simple actually.

    You just reply to the sender:

    sender().tell(yourResponse)
    

    Since you are using the ask-Pattern, this response will not be received by the actual initiator of the ask, but by the onSuccessHandler.