Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

actor replying to non-actor

Tags:

java

akka

I'm just beginning with AKKA and have a basic question about how non-actor code talks to actor code.

How can non-actor code call an actor and get a response ? I've tried calling the actor from the non-actor using Patterns.ask but this doesn't work because there is no 'sender' to which the actor can respond.

So how am I supposed to do it ?

like image 284
BillyBadBoy Avatar asked Aug 14 '13 10:08

BillyBadBoy


1 Answers

This should work just fine. When you use ask, a lightweight actor (I believe represented by a PromiseActorRef) is created to represent the sender so that a response can be sent back that will complete the Future that is created via ask. A little example to show this in action. First the test actor:

class TestActor extends UntypedActor{
  public TestActor(){

  }

  public void onReceive(Object msg){
    getContext().sender().tell("bar", getContext().self());
  }
}

Then the non-actor code that will call it

import java.util.concurrent.TimeUnit;
import scala.concurrent.Await;
import scala.concurrent.Future;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.pattern.Patterns;
import akka.util.Timeout;

public class AskTest {

  public static void main(String[] args) throws Exception{
    ActorSystem sys = ActorSystem.apply("test");
    ActorRef ref = sys.actorOf(Props.create(TestActor.class), "mytest");        
    Timeout t = new Timeout(5, TimeUnit.SECONDS);
    Future<Object> fut = Patterns.ask(ref, "foo", t);
    String response = (String)Await.result(fut, t.duration());
    System.out.println(response);
  }
} 
like image 156
cmbaxter Avatar answered Oct 20 '22 00:10

cmbaxter