Baradé
Baradé

Reputation: 1342

What happens to unmatched messages with Akka?

The Akka documentation says that the mailbox is NOT scanned for messages. Each message is handled after another (FIFO by default) in the order of their arrival. However, when I send a message from an actor to another which is not matched be the receiving actor, it is neither moved to the deadletters actor (which would appear in the log I suppose) nor does it block handling the next message in the mailbox which arrives one second later and can be handled correctly.

What does happen to the unmatched message from the mailbox?

I am using Scala 2.10.4 and Akka 2.4-SNAPSHOT in sbt.

package main.scala

import akka.actor._

class SRActor(dest: ActorRef) extends Actor with ActorLogging {
  dest ! A
  dest ! B

  context.stop(self)

  override def receive = {
    case _ => {
      log.info("Finally got something")
    }
  }
}

class SRActorReceiver extends Actor with ActorLogging {
  override def receive = {
    case B =>
      log.info("Finally got B")
  }
}

Actor creation:

package main.scala

import akka.actor._
case object A
case object B

object ErrorApp extends App {
// SR: Send nowhere received
  var system6 = ActorSystem("ErrorActorSystem")
  val srActorReceiver = system6.actorOf(Props(classOf[SRActorReceiver]), "sractorreceiver")
  val sractor = system6.actorOf(Props(classOf[SRActor], srActorReceiver), "sractor")

  // wait until actors have finished
  Thread.sleep(1000)

  system6.shutdown

Upvotes: 5

Views: 2951

Answers (1)

Łukasz
Łukasz

Reputation: 8673

Copied from docs

Please note that the Akka Actor receive message loop is exhaustive, which is different compared to Erlang and the late Scala Actors. This means that you need to provide a pattern match for all messages that it can accept and if you want to be able to handle unknown messages then you need to have a default case as in the example above. Otherwise an akka.actor.UnhandledMessage(message, sender, recipient) will be published to the ActorSystem's EventStream.

There is also unhandled method in Actor trait that you can override. (docs)

def unhandled(message: Any): Unit

User overridable callback.

Is called when a message isn't handled by the current behavior of the actor by default it fails with either a akka.actor.DeathPactException (in case of an unhandled akka.actor.Terminated message) or publishes an akka.actor.UnhandledMessage to the actor's system's akka.event.EventStream

Upvotes: 5

Related Questions