Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka Java - Creating recursive child actors on the fly?

Tags:

java

akka

It is my understanding that the onReceive can only be executed by one thread at any given point in time.

Let's say I have an untyped actor defined like this:

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;


public class ExampleActor extends UntypedActor {

     private ActorRef databaseActor;


    @Override
    public void preStart() {
       ActorRef databaseActor = getContext().system().actorOf(Props.create(DatabaseActor.class));
    }


    @Override
    public void onReceive(Object message) throws Exception {

        if (message.equals("start")) {
            // spawn a child actor of myself!
            ActorRef child = getContext().actorOf(Props.create(ExampleActor.class));
            databaseActor.tell("fetch", child);
        }

        if (message.equals("dbresponse")) {
           // just log the repsonse here!
        }

        if (message.equals("something else")) {
           // possibly mutate state
        }


   }
}

I essentially want to use Akka without using futures. At the same time, I want my actors to NOT block as much as possible. Is it OK to spawn recursive child actors in my onReceive, soley for handling specific messages from other actors?

Essentially in my "if (message.equals("dbresponse"))", I want to just log a DB response and not mutate state in my ExampleActor.

Will this approach work? What are the consequences of creating actors on the fly like this?

like image 583
HiChews123 Avatar asked May 08 '14 07:05

HiChews123


1 Answers

You are doing it exactly right, this is how the Actor Model foresees handling of actor interactions. Using the ask pattern does something which is effectively the same (but an optimized form of single-reply actor is spawned instead), so if you do not want to use Futures this is the way to opt out.

like image 148
Roland Kuhn Avatar answered Oct 13 '22 17:10

Roland Kuhn