简体   繁体   中英

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)???

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM