문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top