Adding Stash section in Actors docs. Including example added to ActorDocSpec.

This commit is contained in:
phaller 2012-06-12 15:51:54 +02:00
parent d5fb35eee1
commit f385380cc2
2 changed files with 62 additions and 0 deletions

View file

@ -627,6 +627,48 @@ Here's how you use the ``unbecome`` method:
} }
Stash
=====
The `Stash` trait enables an actor to temporarily stash away messages
that can not or should not be handled using the actor's current
behavior. Upon changing the actor's message handler, i.e., right
before invoking ``context.become`` or ``context.unbecome``, all
stashed messages can be "unstashed" by prepending them to the actor's
mailbox. This way, the stashed messages can be processed in the same
order as they have been received originally.
.. warning::
Please note that the ``Stash`` can only be used together with actors
that have a deque-based mailbox. For this, configure the
``mailbox-type`` of the dispatcher to be a deque-based mailbox, such as
``akka.dispatch.UnboundedDequeBasedMailbox``.
Here is an example of the ``Stash`` in action:
.. includecode:: code/docs/actor/ActorDocSpec.scala#stash
Invoking ``stash()`` adds the current message (the message that the
actor received last) to the actor's stash. It is typically invoked
when handling the default case in the actor's message handler to stash
messages that aren't handled by the other cases. It is illegal to
stash the same message twice; to do so results in a
``IllegalStateException`` being thrown. The stash may also be bounded
in which case invoking ``stash()`` may lead to a capacity violation,
which results in a ``StashOverflowException``. The capacity of the
stash can be configured using the ``stash-capacity`` setting (an ``Int``) of the
dispatcher's configuration.
Invoking ``unstashAll()`` enqueues messages from the stash to the
actor's mailbox until the capacity of the mailbox (if any) has been
reached (note that messages from the stash are prepended to the
mailbox). In case a bounded mailbox overflows, a
``MessageQueueAppendFailedException`` is thrown.
The stash is guaranteed to be empty after calling ``unstashAll()``.
Killing an Actor Killing an Actor
================ ================

View file

@ -300,6 +300,26 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
val actor = system.actorOf(Props(new HotSwapActor), name = "hot") val actor = system.actorOf(Props(new HotSwapActor), name = "hot")
} }
"using Stash" in {
//#stash
import akka.actor.Stash
class ActorWithProtocol extends Actor with Stash {
def receive = {
case "open"
unstashAll()
context.become {
case "write" // do writing...
case "close"
unstashAll()
context.unbecome()
case msg stash()
}
case msg stash()
}
}
//#stash
}
"using watch" in { "using watch" in {
//#watch //#watch
import akka.actor.{ Actor, Props, Terminated } import akka.actor.{ Actor, Props, Terminated }