Made a pass through Actor docs

This commit is contained in:
Derek Williams 2011-04-11 21:12:44 -06:00
parent 171c8c8bc2
commit 4ccf4f869f

View file

@ -1,27 +1,26 @@
Actors (Scala) Actors (Scala)
============== ==============
=
Module stability: **SOLID** Module stability: **SOLID**
The `Actor Model <http://en.wikipedia.org/wiki/Actor_model>`_ provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management, making it easier to write correct concurrent and parallel systems. Actors were defined in the 1973 paper by Carl Hewitt but have been popularized by the Erlang language, and used for example at Ericsson with great success to build highly concurrent and reliable telecom systems. The `Actor Model <http://en.wikipedia.org/wiki/Actor_model>`_ provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management, making it easier to write correct concurrent and parallel systems. Actors were defined in the 1973 paper by Carl Hewitt but have been popularized by the Erlang language, and used for example at Ericsson with great success to build highly concurrent and reliable telecom systems.
The API of Akkas Actors is similar to Scala Actors which has borrowed some of its syntax from Erlang. The API of Akkas Actors is similar to Scala Actors which has borrowed some of its syntax from Erlang.
The Akka 0.9 release introduced a new concept; ActorRef, which requires some refactoring. If you are new to Akka just read along, but if you have used Akka 0.6.x, 0.7.x and 0.8.x then you might be helped by the `0.8.x => 0.9.x migration guide <migration-guide-0.8.x-0.9.x>`_ The Akka 0.9 release introduced a new concept; ActorRef, which requires some refactoring. If you are new to Akka just read along, but if you have used Akka 0.6.x, 0.7.x and 0.8.x then you might be helped by the :doc:`0.8.x => 0.9.x migration guide <migration-guide-0.8.x-0.9.x>`
Creating Actors Creating Actors
--------------- ---------------
Actors can be created either by: Actors can be created either by:
* Extending the Actor class and implementing the receive method. * Extending the Actor class and implementing the receive method.
* Create an anonymous actor using one of the actor methods. * Create an anonymous actor using one of the actor methods.
Defining an Actor class Defining an Actor class
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
Actor classes are implemented by extending the Actor class and implementing the 'receive' method. The 'receive' method should definie a series of case statements (which has the type 'PartialFunction[Any, Unit]') that defines which messages your Actor can handle, using standard Scala pattern matching, along with the implementation of how the messages should be processed. Actor classes are implemented by extending the Actor class and implementing the ``receive`` method. The ``receive`` method should define a series of case statements (which has the type ``PartialFunction[Any, Unit]``) that defines which messages your Actor can handle, using standard Scala pattern matching, along with the implementation of how the messages should be processed.
Here is an example: Here is an example:
@ -34,9 +33,7 @@ Here is an example:
} }
} }
Please note that the Akka Actor 'receive' message loop is exhaustive, which is different compared to Erlang and 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. Please note that the Akka Actor ``receive`` message loop is exhaustive, which is different compared to Erlang and 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.
The 'Actor' trait mixes in the 'akka.util.Logging' trait which defines a logger in the 'log' field that you can use to log. This logger is configured in the 'akka.conf' configuration file (and is based on the Configgy library which is using Java Logging).
Creating Actors Creating Actors
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
@ -46,7 +43,7 @@ Creating Actors
val myActor = Actor.actorOf[MyActor] val myActor = Actor.actorOf[MyActor]
myActor.start myActor.start
Normally you would want to import the 'actorOf' method like this: Normally you would want to import the ``actorOf`` method like this:
.. code-block:: scala .. code-block:: scala
@ -54,7 +51,7 @@ Normally you would want to import the 'actorOf' method like this:
val myActor = actorOf[MyActor] val myActor = actorOf[MyActor]
To avoid prefixing it with 'Actor' every time you use it. To avoid prefixing it with ``Actor`` every time you use it.
You can also start it in the same statement: You can also start it in the same statement:
@ -62,12 +59,12 @@ You can also start it in the same statement:
val myActor = actorOf[MyActor].start val myActor = actorOf[MyActor].start
The call to 'actorOf' returns an instance of 'ActorRef'. This is a handle to the 'Actor' instance which you can use to interact with the Actor, like send messages to it etc. more on this shortly. The 'ActorRef' is immutable and has a one to one relationship with the Actor it represents. The 'ActorRef' is also serializable and network-aware. This means that you can serialize it, send it over the wire and use it on a remote host and it will still be representing the same Actor on the original node, across the network. The call to ``actorOf`` returns an instance of ``ActorRef``. This is a handle to the ``Actor`` instance which you can use to interact with the ``Actor``. The ``ActorRef`` is immutable and has a one to one relationship with the Actor it represents. The ``ActorRef`` is also serializable and network-aware. This means that you can serialize it, send it over the wire and use it on a remote host and it will still be representing the same Actor on the original node, across the network.
Creating Actors with non-default constructor Creating Actors with non-default constructor
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If your Actor has a constructor that takes parameters then you can't create it using 'actorOf[TYPE]'. Instead you can use a variant of 'actorOf' that takes a call-by-name block in which you can create the Actor in any way you like. If your Actor has a constructor that takes parameters then you can't create it using ``actorOf[TYPE]``. Instead you can use a variant of ``actorOf`` that takes a call-by-name block in which you can create the Actor in any way you like.
Here is an example: Here is an example:
@ -90,10 +87,11 @@ Identifying Actors
------------------ ------------------
Each Actor has two fields: Each Actor has two fields:
* self.uuid
* self.id
The difference is that the 'uuid' is generated by the runtime, guaranteed to be unique and can't be modified. While the 'id' is modifiable by the user, and defaults to the Actor class name. You can retrieve Actors by both UUID and ID using the 'ActorRegistry', see the section further down for details. * ``self.uuid``
* ``self.id``
The difference is that the ``uuid`` is generated by the runtime, guaranteed to be unique and can't be modified. While the ``id`` is modifiable by the user, and defaults to the Actor class name. You can retrieve Actors by both UUID and ID using the ``ActorRegistry``, see the section further down for details.
Messages and immutability Messages and immutability
------------------------- -------------------------
@ -110,21 +108,22 @@ Here is an example:
// create a new case class message // create a new case class message
val message = Register(user) val message = Register(user)
Other good messages types are 'scala.Tuple2', 'scala.List', 'scala.Map' which are all immutable and great for pattern matching. Other good messages types are ``scala.Tuple2``, ``scala.List``, ``scala.Map`` which are all immutable and great for pattern matching.
Send messages Send messages
------------- -------------
Messages are sent to an Actor through one of the “bang” methods. Messages are sent to an Actor through one of the “bang” methods.
* ! means “fire-and-forget”, e.g. send a message asynchronously and return immediately.
* !! means “send-and-reply-eventually”, e.g. send a message asynchronously and wait for a reply through aFuture. Here you can specify a timeout. Using timeouts is very important. If no timeout is specified then the actors default timeout (set by the this.timeout variable in the actor) is used. This method returns an 'Option[Any]' which will be either 'Some(result)' if returning successfully or None if the call timed out.
* !!! sends a message asynchronously and returns a 'Future'.
You can check if an Actor can handle a specific message by invoking the 'isDefinedAt' method: * ! means “fire-and-forget”, e.g. send a message asynchronously and return immediately.
* !! means “send-and-reply-eventually”, e.g. send a message asynchronously and wait for a reply through aFuture. Here you can specify a timeout. Using timeouts is very important. If no timeout is specified then the actors default timeout (set by the this.timeout variable in the actor) is used. This method returns an ``Option[Any]`` which will be either ``Some(result)`` if returning successfully or None if the call timed out.
* !!! sends a message asynchronously and returns a ``Future``.
You can check if an Actor can handle a specific message by invoking the ``isDefinedAt`` method:
.. code-block:: scala .. code-block:: scala
if (actor.isDefinedAt(message) actor ! message if (actor.isDefinedAt(message)) actor ! message
else ... else ...
Fire-forget Fire-forget
@ -136,21 +135,21 @@ This is the preferred way of sending messages. No blocking waiting for a message
actor ! "Hello" actor ! "Hello"
If invoked from within an Actor, then the sending actor reference will be implicitly passed along with the message and available to the receiving Actor in its 'sender: Option[AnyRef]' member field. He can use this to reply to the original sender or use the 'reply(message: Any)' method. If invoked from within an Actor, then the sending actor reference will be implicitly passed along with the message and available to the receiving Actor in its ``sender: Option[AnyRef]`` member field. He can use this to reply to the original sender or use the ``reply(message: Any)`` method.
If invoked from an instance that is **not** an Actor there will be no implicit sender passed along the message and you will get an IllegalStateException if you call 'self.reply(..)'. If invoked from an instance that is **not** an Actor there will be no implicit sender passed along the message and you will get an IllegalStateException if you call ``self.reply(..)``.
Send-And-Receive-Eventually Send-And-Receive-Eventually
^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Using '!!' will send a message to the receiving Actor asynchronously but it will wait for a reply on a 'Future', blocking the sender Actor until either: Using ``!!`` will send a message to the receiving Actor asynchronously but it will wait for a reply on a ``Future``, blocking the sender Actor until either:
* A reply is received, or * A reply is received, or
* The Future times out * The Future times out
You can pass an explicit time-out to the '!!' method and if none is specified then the default time-out defined in the sender Actor will be used. You can pass an explicit time-out to the ``!!`` method and if none is specified then the default time-out defined in the sender Actor will be used.
The '!!' method returns an 'Option[Any]' which will be either 'Some(result)' if returning successfully, or None if the call timed out. The ``!!`` method returns an ``Option[Any]`` which will be either ``Some(result)`` if returning successfully, or ``None`` if the call timed out.
Here are some examples: Here are some examples:
.. code-block:: scala .. code-block:: scala
@ -172,7 +171,7 @@ Here are some examples:
Send-And-Receive-Future Send-And-Receive-Future
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
Using '!!!' will send a message to the receiving Actor asynchronously and will return a 'Future': Using ``!!!`` will send a message to the receiving Actor asynchronously and will return a 'Future':
.. code-block:: scala .. code-block:: scala
@ -192,15 +191,15 @@ You can forward a message from one actor to another. This means that the origina
Receive messages Receive messages
---------------- ----------------
An Actor has to implement the receive method to receive messages: An Actor has to implement the ``receive`` method to receive messages:
.. code-block:: scala .. code-block:: scala
protected def receive: PartialFunction[Any, Unit] protected def receive: PartialFunction[Any, Unit]
Note: Akka has an alias to the 'PartialFunction[Any, Unit]' type called 'Receive' (akka.actor.Actor.Receive), so you can use this type instead for clarity. But most often you don't need to spell it out. Note: Akka has an alias to the ``PartialFunction[Any, Unit]`` type called ``Receive`` (``akka.actor.Actor.Receive``), so you can use this type instead for clarity. But most often you don't need to spell it out.
This method should return a PartialFunction, e.g. a match/case clause in which the message can be matched against the different case clauses using Scala pattern matching. Here is an example: This method should return a ``PartialFunction``, e.g. a match/case clause in which the message can be matched against the different case clauses using Scala pattern matching. Here is an example:
.. code-block:: scala .. code-block:: scala
@ -218,22 +217,24 @@ Actor internal API
------------------ ------------------
The Actor trait contains almost no member fields or methods to invoke, you just use the Actor trait to implement the: The Actor trait contains almost no member fields or methods to invoke, you just use the Actor trait to implement the:
# 'receive' message handler
# life-cycle callbacks:
## preStart
## postStop
## preRestart
## postRestart
The 'Actor' trait has one single member field (apart from the 'log' field from the mixed in 'Logging' trait): #. ``receive`` message handler
#. life-cycle callbacks:
#. preStart
#. postStop
#. preRestart
#. postRestart
The ``Actor`` trait has one single member field (apart from the ``log`` field from the mixed in ``Logging`` trait):
.. code-block:: scala .. code-block:: scala
val self: ActorRef val self: ActorRef
This 'self' field holds a reference to its 'ActorRef' and it is this reference you want to access the Actor's API. Here, for example, you find methods to reply to messages, send yourself messages, define timeouts, fault tolerance etc., start and stop etc. This ``self`` field holds a reference to its ``ActorRef`` and it is this reference you want to access the Actor's API. Here, for example, you find methods to reply to messages, send yourself messages, define timeouts, fault tolerance etc., start and stop etc.
However, for convenience you can import these functions and fields like below, which will allow you do drop the 'self' prefix: However, for convenience you can import these functions and fields like below, which will allow you do drop the ``self`` prefix:
.. code-block:: scala .. code-block:: scala
@ -245,17 +246,17 @@ However, for convenience you can import these functions and fields like below, w
... ...
} }
But in this documentation we will always prefix the calls with 'self' for clarity. But in this documentation we will always prefix the calls with ``self`` for clarity.
Let's start by looking how we can reply to messages in a convenient way using this 'ActorRef' API. Let's start by looking how we can reply to messages in a convenient way using this ``ActorRef`` API.
Reply to messages Reply to messages
----------------- -----------------
Reply using the reply and reply_? methods Reply using the reply and reply\_? methods
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you want to send a message back to the original sender of the message you just received then you can use the 'reply(..)' method. If you want to send a message back to the original sender of the message you just received then you can use the ``reply(..)`` method.
.. code-block:: scala .. code-block:: scala
@ -263,9 +264,9 @@ If you want to send a message back to the original sender of the message you jus
val result = process(request) val result = process(request)
self.reply(result) self.reply(result)
In this case the 'result' will be send back to the Actor that sent the 'request'. In this case the ``result`` will be send back to the Actor that sent the ``request``.
The 'reply' method throws an 'IllegalStateException' if unable to determine what to reply to, e.g. the sender is not an actor. You can also use the more forgiving 'reply_?' method which returns 'true' if reply was sent, and 'false' if unable to determine what to reply to. The ``reply`` method throws an ``IllegalStateException`` if unable to determine what to reply to, e.g. the sender is not an actor. You can also use the more forgiving ``reply_?`` method which returns ``true`` if reply was sent, and ``false`` if unable to determine what to reply to.
.. code-block:: scala .. code-block:: scala
@ -277,7 +278,7 @@ The 'reply' method throws an 'IllegalStateException' if unable to determine what
Reply using the sender reference Reply using the sender reference
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If the sender is an Actor then its reference will be implicitly passed along together with the message and will end up in the 'sender: Option[ActorRef]' member field in the 'ActorRef. This means that you can use this field to send a message back to the sender. If the sender is an Actor then its reference will be implicitly passed along together with the message and will end up in the ``sender: Option[ActorRef]`` member field in the ``ActorRef``. This means that you can use this field to send a message back to the sender.
.. code-block:: scala .. code-block:: scala
@ -286,7 +287,7 @@ If the sender is an Actor then its reference will be implicitly passed along tog
val result = process(request) val result = process(request)
self.sender.get ! result self.sender.get ! result
It's important to know that 'sender.get' will throw an exception if the 'sender' is not defined, e.g. the 'Option' is 'None'. You can check if it is defined by invoking the 'sender.isDefined' method, but a more elegant solution is to use 'foreach' which will only be executed if the sender is defined in the 'sender' member 'Option' field. If it is not, then the operation in the 'foreach' method is ignored. It's important to know that ``sender.get`` will throw an exception if the ``sender`` is not defined, e.g. the ``Option`` is ``None``. You can check if it is defined by invoking the ``sender.isDefined`` method, but a more elegant solution is to use ``foreach`` which will only be executed if the sender is defined in the ``sender`` member ``Option`` field. If it is not, then the operation in the ``foreach`` method is ignored.
.. code-block:: scala .. code-block:: scala
@ -295,14 +296,14 @@ It's important to know that 'sender.get' will throw an exception if the 'sender'
val result = process(request) val result = process(request)
self.sender.foreach(_ ! result) self.sender.foreach(_ ! result)
The same pattern holds for using the 'senderFuture' in the section below. The same pattern holds for using the ``senderFuture`` in the section below.
Reply using the sender future Reply using the sender future
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If a message was sent with the '!!' or '!!!' methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the 'reply' method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it. If a message was sent with the ``!!`` or ``!!!`` methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the ``reply`` method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it.
The reference to the Future resides in the 'senderFuture: Option[CompletableFuture[]]' member field in the 'ActorRef' class. The reference to the Future resides in the ``senderFuture: Option[CompletableFuture[_]]`` member field in the ``ActorRef`` class.
Here is an example of how it can be used: Here is an example of how it can be used:
@ -320,8 +321,8 @@ Here is an example of how it can be used:
Reply using the channel Reply using the channel
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
If you want to have a handle to an object to whom you can reply to the message, you can use the Channel abstraction. If you want to have a handle to an object to whom you can reply to the message, you can use the ``Channel`` abstraction.
Simply call self.channel and then you can forward that to others, store it away or otherwise until you want to reply, which you do by 'Channel ! response': Simply call ``self.channel`` and then you can forward that to others, store it away or otherwise until you want to reply, which you do by ``Channel ! response``:
.. code-block:: scala .. code-block:: scala
@ -337,16 +338,16 @@ Simply call self.channel and then you can forward that to others, store it away
Summary of reply semantics and options Summary of reply semantics and options
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* self.reply(...) can be used to reply to an Actor or a Future. * ``self.reply(...)`` can be used to reply to an ``Actor`` or a ``Future``.
* self.sender is a reference to the actor you can reply to, if it exists * ``self.sender`` is a reference to the ``Actor`` you can reply to, if it exists
* self.senderFuture is a reference to the future you can reply to, if it exists * ``self.senderFuture`` is a reference to the ``Future`` you can reply to, if it exists
* self.channel is a reference providing an abstraction to either self.sender or self.senderFuture if one is set, providing a single reference to store and reply to (the reference equivalent to the 'reply(...)' method). * ``self.channel`` is a reference providing an abstraction to either ``self.sender`` or ``self.senderFuture`` if one is set, providing a single reference to store and reply to (the reference equivalent to the ``reply(...)`` method).
* self.sender and self.senderFuture will never be set at the same time, as there can only be one reference to accept a reply. * ``self.sender`` and ``self.senderFuture`` will never be set at the same time, as there can only be one reference to accept a reply.
Initial receive timeout Initial receive timeout
----------------------- -----------------------
A timeout mechanism can be used to receive a message when no initial message is received within a certain time. To receive this timeout you have to set the 'receiveTimeout' property and declare a case handing the ReceiveTimeout object. A timeout mechanism can be used to receive a message when no initial message is received within a certain time. To receive this timeout you have to set the ``receiveTimeout`` property and declare a case handing the ReceiveTimeout object.
.. code-block:: scala .. code-block:: scala
@ -359,25 +360,25 @@ A timeout mechanism can be used to receive a message when no initial message is
throw new RuntimeException("received timeout") throw new RuntimeException("received timeout")
} }
This mechanism also work for hotswapped receive functions. Every time a 'HotSwap' is sent, the receive timeout is reset and rescheduled. This mechanism also work for hotswapped receive functions. Every time a ``HotSwap`` is sent, the receive timeout is reset and rescheduled.
Starting actors Starting actors
--------------- ---------------
Actors are started by invoking the start method. Actors are started by invoking the ``start`` method.
.. code-block:: scala .. code-block:: scala
val actor = actorOf[MyActor] val actor = actorOf[MyActor]
actor.start actor.start
You can create and start the Actor in a oneliner like this: You can create and start the ``Actor`` in a oneliner like this:
.. code-block:: scala .. code-block:: scala
val actor = actorOf[MyActor].start val actor = actorOf[MyActor].start
When you start the actor then it will automatically call the 'def preStart' callback method on the 'Actor' trait. This is an excellent place to add initialization code for the actor. When you start the ``Actor`` then it will automatically call the ``def preStart`` callback method on the ``Actor`` trait. This is an excellent place to add initialization code for the actor.
.. code-block:: scala .. code-block:: scala
@ -388,13 +389,13 @@ When you start the actor then it will automatically call the 'def preStart' call
Stopping actors Stopping actors
--------------- ---------------
Actors are stopped by invoking the stop method. Actors are stopped by invoking the ``stop`` method.
.. code-block:: scala .. code-block:: scala
actor.stop actor.stop
When stop is called then a calll to the def postStop callback method will take place. The Actor can use this callback to implement shutdown behavior. When stop is called then a call to the ``def postStop`` callback method will take place. The ``Actor`` can use this callback to implement shutdown behavior.
.. code-block:: scala .. code-block:: scala
@ -408,14 +409,13 @@ You can shut down all Actors in the system by invoking:
Actor.registry.shutdownAll Actor.registry.shutdownAll
-
PoisonPill PoisonPill
---------- ----------
You can also send an actor the 'akka.actor.PoisonPill' message, which will stop the actor when the message is processed. You can also send an actor the ``akka.actor.PoisonPill`` message, which will stop the actor when the message is processed.
If the sender is a 'Future' (e.g. the message is sent with '!!' or '!!!'), the 'Future' will be completed with an 'akka.actor.ActorKilledException("PoisonPill")'. If the sender is a ``Future`` (e.g. the message is sent with ``!!`` or ``!!!``), the ``Future`` will be completed with an ``akka.actor.ActorKilledException("PoisonPill")``.
HotSwap HotSwap
------- -------
@ -424,12 +424,13 @@ Upgrade
^^^^^^^ ^^^^^^^
Akka supports hotswapping the Actors message loop (e.g. its implementation) at runtime. There are two ways you can do that: Akka supports hotswapping the Actors message loop (e.g. its implementation) at runtime. There are two ways you can do that:
* Send a 'HotSwap' message to the Actor
* Invoke the 'become' method from within the Actor.
Both of these takes a 'ActorRef => PartialFunction[Any, Unit]' that implements the new message handler. The hotswapped code is kept in a Stack which can be pushed and popped. * Send a ``HotSwap`` message to the Actor.
* Invoke the ``become`` method from within the Actor.
To hotswap the Actor body using the 'HotSwap' message: Both of these takes a ``ActorRef => PartialFunction[Any, Unit]`` that implements the new message handler. The hotswapped code is kept in a Stack which can be pushed and popped.
To hotswap the Actor body using the ``HotSwap`` message:
.. code-block:: scala .. code-block:: scala
@ -437,9 +438,9 @@ To hotswap the Actor body using the 'HotSwap' message:
case message => self.reply("hotswapped body") case message => self.reply("hotswapped body")
}) })
Using the 'HotSwap' message for hotswapping has its limitations. You can not replace it with any code that uses the Actor's 'self' reference. If you need to do that the the 'become' method is better. Using the ``HotSwap`` message for hotswapping has its limitations. You can not replace it with any code that uses the Actor's ``self`` reference. If you need to do that the the ``become`` method is better.
To hotswap the Actor using 'become': To hotswap the Actor using ``become``:
.. code-block:: scala .. code-block:: scala
@ -458,9 +459,9 @@ To hotswap the Actor using 'become':
case "bar" => become(happy) case "bar" => become(happy)
} }
The 'become' method is useful for many different things, but a particular nice example of it is in example where it is used to implement a Finite State Machine (FSM): `Dining Hakkers <http://github.com/jboner/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnBecome.scala>`_ The ``become`` method is useful for many different things, but a particular nice example of it is in example where it is used to implement a Finite State Machine (FSM): `Dining Hakkers <http://github.com/jboner/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnBecome.scala>`_
Here is another little cute example of 'become' and 'unbecome' in action: Here is another little cute example of ``become`` and ``unbecome`` in action:
.. code-block:: scala .. code-block:: scala
@ -494,18 +495,18 @@ Downgrade
Since the hotswapped code is pushed to a Stack you can downgrade the code as well. There are two ways you can do that: Since the hotswapped code is pushed to a Stack you can downgrade the code as well. There are two ways you can do that:
* Send the Actor a RevertHotswap message * Send the Actor a ``RevertHotswap`` message
* Invoke the 'unbecome' method from within the Actor. * Invoke the ``unbecome`` method from within the Actor.
Both of these will pop the Stack and replace the Actor's implementation with the PartialFunction[Any, Unit] that is at the top of the Stack. Both of these will pop the Stack and replace the Actor's implementation with the ``PartialFunction[Any, Unit]`` that is at the top of the Stack.
Revert the Actor body using the 'RevertHotSwap' message: Revert the Actor body using the ``RevertHotSwap`` message:
.. code-block:: scala .. code-block:: scala
actor ! RevertHotSwap actor ! RevertHotSwap
Revert the Actor body using the 'unbecome' method: Revert the Actor body using the ``unbecome`` method:
.. code-block:: scala .. code-block:: scala
@ -516,7 +517,7 @@ Revert the Actor body using the 'unbecome' method:
Killing an Actor Killing an Actor
---------------- ----------------
You can kill an actor by sending a 'Kill' message. This will restart the actor through regular supervisor semantics. You can kill an actor by sending a ``Kill`` message. This will restart the actor through regular supervisor semantics.
Use it like this: Use it like this:
@ -539,7 +540,7 @@ The actor has a well-defined non-circular life-cycle.
Extending Actors using PartialFunction chaining Extending Actors using PartialFunction chaining
----------------------------------------------- -----------------------------------------------
A bit advanced but very useful way of defining a base message handler and then extend that, either through inheritance or delegation, is to use 'PartialFunction' 'orElse' chaining. A bit advanced but very useful way of defining a base message handler and then extend that, either through inheritance or delegation, is to use ``PartialFunction.orElse`` chaining.
In generic base Actor: In generic base Actor:
@ -561,12 +562,12 @@ In generic base Actor:
In subclassing Actor: In subclassing Actor:
`<code format="scala">`_ .. code-block:: scala
class SpecificActor extends GenericActor {
class SpecificActor extends GenericActor {
def specificMessageHandler = { def specificMessageHandler = {
case event: MyMsg => printf("specific: %s\n", event.subject) case event: MyMsg => printf("specific: %s\n", event.subject)
} }
} }
case class MyMsg(subject: String) case class MyMsg(subject: String)
`<code>`_