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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With