metaphori
metaphori

Reputation: 2811

Untyped Actors (Java+Akka): requeuing unhandled messages

I'm creating a system of actors using Java+Akka. In particular, I define untyped actors by providing an implementation of the onReceive() method.

In that method, I implement the behavior of the actor by defining the logic to be executed upon reception of a message. It may be something as:

public void onReceive(Object msg) throws Exception {
  if(msg instanceof MsgType1){ ... }
  else if(msg instanceof MsgType2){ ... }
  else unhandled(msg);
}

However, what if the actor is interested in only a single type of msg? Is it possible to implement a selective receive, so that the actor waits for a certain msg (and the system automatically re-queues all the other types of messages)???

Upvotes: 1

Views: 861

Answers (1)

Marius Danila
Marius Danila

Reputation: 10431

This "a la Erlang" message processing mode is not available in Akka AFAIK. However, you can use Stash to obtain the effect you want.

So the code would look like this

public void onReceive(Object msg) throws Exception {
    if(msg instanceof MsgType1){ ... }
    else if(msg instanceof MsgType2){ ... }
    else stash();
}

At some point in the message handling you would switch to another state (presumably by calling getContext().become). You would also do a unstashAll() call in order to re-append the messages you ignored until that point back to the mailbox.

Upvotes: 3

Related Questions