2011-10-05 17:41:00 +02:00
2011-05-10 09:53:58 +02:00
.. _actors-scala:
2011-10-05 17:41:00 +02:00
################
Actors (Scala)
################
2011-04-26 21:11:58 +02:00
2011-10-05 17:41:00 +02:00
The `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 Akka’ s Actors is similar to Scala Actors which has borrowed some of
its syntax from Erlang.
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
.. _Actor Model: http://en.wikipedia.org/wiki/Actor_model
2011-04-09 19:55:46 -06:00
Creating Actors
2011-10-05 17:41:00 +02:00
===============
2011-04-09 19:55:46 -06:00
2011-12-28 13:09:56 +01:00
Since Akka enforces parental supervision every actor is supervised and
(potentially) the supervisor of its children; it is advisable that you
familiarize yourself with :ref: `actor-systems` and :ref: `supervision` and it
may also help to read :ref: `actorOf-vs-actorFor` .
2011-10-05 17:41:00 +02:00
2011-04-09 19:55:46 -06:00
Defining an Actor class
2011-10-05 17:41:00 +02:00
-----------------------
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
Actor classes are implemented by extending the Actor class and implementing the
2011-12-06 16:49:39 +01:00
:meth: `receive` method. The :meth: `receive` method should define a series of case
2011-10-05 17:41:00 +02:00
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.
2011-04-09 19:55:46 -06:00
Here is an example:
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala
2011-12-06 16:49:39 +01:00
:include: imports1,my-actor
2011-09-21 23:41:52 +02:00
2011-10-05 17:41:00 +02:00
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
2011-12-20 11:19:06 +01:00
the example above. Otherwise an `` akka.actor.UnhandledMessage(message, sender, recipient) `` will be
2011-12-20 10:38:37 +01:00
published to the `` ActorSystem `` 's `` EventStream `` .
2011-04-09 19:55:46 -06:00
2011-12-08 14:06:20 +01:00
Creating Actors with default constructor
----------------------------------------
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala
2011-12-14 19:25:32 +01:00
:include: imports2,system-actorOf
2011-04-09 19:55:46 -06:00
2011-12-06 16:49:39 +01:00
The call to :meth: `actorOf` returns an instance of `` ActorRef `` . This is a handle to
2011-10-05 17:41:00 +02:00
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.
2011-04-09 19:55:46 -06:00
2011-12-06 16:49:39 +01:00
In the above example the actor was created from the system. It is also possible
to create actors from other actors with the actor `` context `` . The difference is
how the supervisor hierarchy is arranged. When using the context the current actor
will be supervisor of the created child actor. When using the system it will be
a top level actor, that is supervised by the system (internal guardian actor).
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#context-actorOf
2011-12-06 16:49:39 +01:00
2011-12-16 00:39:29 +01:00
The name parameter is optional, but you should preferably name your actors, since
that is used in log messages and for identifying actors. The name must not be empty
or start with `` $ `` . If the given name is already in use by another child to the
same parent actor an `InvalidActorNameException` is thrown.
2011-12-07 16:44:52 +01:00
Actors are automatically started asynchronously when created.
2011-12-13 14:09:40 +01:00
When you create the `` Actor `` then it will automatically call the `` preStart ``
2011-12-08 14:06:20 +01:00
callback method on the `` Actor `` trait. This is an excellent place to
add initialization code for the actor.
.. code-block :: scala
override def preStart() = {
... // initialization code
}
2011-04-09 19:55:46 -06:00
Creating Actors with non-default constructor
2011-10-05 17:41:00 +02:00
--------------------------------------------
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
If your Actor has a constructor that takes parameters then you can't create it
2011-12-13 14:53:18 +01:00
using `` actorOf(Props[TYPE]) `` . Instead you can use a variant of `` actorOf `` that takes
2011-10-05 17:41:00 +02:00
a call-by-name block in which you can create the Actor in any way you like.
2011-04-09 19:55:46 -06:00
Here is an example:
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#creating-constructor
2011-04-09 19:55:46 -06:00
2012-05-25 17:55:25 +02:00
.. warning ::
You might be tempted at times to offer an `` Actor `` factory which always
returns the same instance, e.g. by using a `` lazy val `` or an
2012-05-25 18:11:47 +02:00
`` object ... extends Actor `` . This is not supported, as it goes against the
2012-05-25 17:55:25 +02:00
meaning of an actor restart, which is described here:
:ref: `supervision-restart` .
2011-04-09 19:55:46 -06:00
2011-12-14 14:05:44 +01:00
Props
-----
2011-12-14 15:10:42 +01:00
`` Props `` is a configuration class to specify options for the creation
2011-12-14 14:05:44 +01:00
of actors. Here are some examples on how to create a `` Props `` instance.
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#creating-props-config
2011-12-14 14:05:44 +01:00
2011-12-06 16:49:39 +01:00
Creating Actors with Props
--------------------------
2011-12-14 15:10:42 +01:00
Actors are created by passing in a `` Props `` instance into the `` actorOf `` factory method.
2011-12-06 16:49:39 +01:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#creating-props
2011-12-06 16:49:39 +01:00
2011-10-16 17:39:23 +02:00
Creating Actors using anonymous classes
2011-12-06 16:49:39 +01:00
---------------------------------------
2011-10-16 17:39:23 +02:00
2011-12-06 16:49:39 +01:00
When spawning actors for specific sub-tasks from within an actor, it may be convenient to include the code to be executed directly in place, using an anonymous class.
2011-10-16 17:39:23 +02:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#anonymous-actor
2011-10-16 17:39:23 +02:00
.. warning ::
In this case you need to carefully avoid closing over the containing actor’ s
reference, i.e. do not call methods on the enclosing actor from within the
anonymous Actor class. This would break the actor encapsulation and may
introduce synchronization bugs and race conditions because the other actor’ s
code will be scheduled concurrently to the enclosing actor. Unfortunately
there is not yet a way to detect these illegal accesses at compile time.
2011-12-08 14:06:20 +01:00
See also: :ref: `jmm-shared-state`
2011-10-16 17:39:23 +02:00
2011-04-09 19:55:46 -06:00
2011-12-07 16:44:52 +01:00
Actor API
=========
2011-04-09 19:55:46 -06:00
2011-12-06 16:49:39 +01:00
The :class: `Actor` trait defines only one abstract method, the above mentioned
:meth: `receive` , which implements the behavior of the actor.
2011-04-09 19:55:46 -06:00
2011-12-23 22:41:48 +01:00
If the current actor behavior does not match a received message,
:meth: `unhandled` is called, which by default publishes an
`` akka.actor.UnhandledMessage(message, sender, recipient) `` on the actor
2012-04-23 15:40:21 +02:00
system’ s event stream (set configuration item
`` akka.event-handler-startup-timeout `` to `` true `` to have them converted into
actual Debug messages)
2011-04-09 19:55:46 -06:00
2011-12-06 16:49:39 +01:00
In addition, it offers:
2011-10-05 17:41:00 +02:00
2011-12-07 16:44:52 +01:00
* :obj: `self` reference to the :class: `ActorRef` of the actor
2011-12-06 16:49:39 +01:00
* :obj: `sender` reference sender Actor of the last received message, typically used as described in :ref: `Actor.Reply`
2012-01-23 17:18:49 +01:00
* :obj: `supervisorStrategy` user overridable definition the strategy to use for supervising child actors
2011-12-06 16:49:39 +01:00
* :obj: `context` exposes contextual information for the actor and the current message, such as:
2011-06-27 19:09:09 +02:00
2011-12-08 14:06:20 +01:00
* factory methods to create child actors (:meth: `actorOf` )
2011-12-06 16:49:39 +01:00
* system that the actor belongs to
* parent supervisor
* supervised children
2011-12-28 13:09:56 +01:00
* lifecycle monitoring
2011-12-06 16:49:39 +01:00
* hotswap behavior stack as described in :ref: `Actor.HotSwap`
You can import the members in the :obj: `context` to avoid prefixing access with `` context. ``
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#import-context
2011-06-27 22:20:09 +02:00
The remaining visible methods are user-overridable life-cycle hooks which are
described in the following::
2011-06-27 19:09:09 +02:00
def preStart() {}
2011-12-14 19:25:32 +01:00
def preRestart(reason: Throwable, message: Option[Any]) {
context.children foreach (context.stop(_))
postStop()
}
2011-12-06 16:49:39 +01:00
def postRestart(reason: Throwable) { preStart() }
2011-06-27 19:09:09 +02:00
def postStop() {}
The implementations shown above are the defaults provided by the :class: `Actor`
trait.
2011-12-28 13:09:56 +01:00
.. _deathwatch-scala:
Lifecycle Monitoring aka DeathWatch
-----------------------------------
In order to be notified when another actor terminates (i.e. stops permanently,
not temporary failure and restart), an actor may register itself for reception
of the :class: `Terminated` message dispatched by the other actor upon
termination (see `Stopping Actors`_ ). This service is provided by the
:class: `DeathWatch` component of the actor system.
Registering a monitor is easy:
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#watch
2011-12-28 13:09:56 +01:00
It should be noted that the :class: `Terminated` message is generated
independent of the order in which registration and termination occur.
Registering multiple times does not necessarily lead to multiple messages being
generated, but there is no guarantee that only exactly one such message is
received: if termination of the watched actor has generated and queued the
message, and another registration is done before this message has been
processed, then a second message will be queued, because registering for
monitoring of an already terminated actor leads to the immediate generation of
the :class: `Terminated` message.
It is also possible to deregister from watching another actor’ s liveliness
using `` context.unwatch(target) `` , but obviously this cannot guarantee
non-reception of the :class: `Terminated` message because that may already have
been queued.
2011-10-05 17:41:00 +02:00
2011-06-27 19:09:09 +02:00
Start Hook
2011-10-05 17:41:00 +02:00
----------
2011-06-27 19:09:09 +02:00
2011-10-05 17:41:00 +02:00
Right after starting the actor, its :meth: `preStart` method is invoked.
2011-06-27 19:09:09 +02:00
::
2011-12-06 16:49:39 +01:00
override def preStart() {
2011-10-05 17:41:00 +02:00
// registering with other actors
2011-06-27 19:09:09 +02:00
someService ! Register(self)
}
2011-10-05 17:41:00 +02:00
2011-06-27 19:09:09 +02:00
Restart Hooks
2011-10-05 17:41:00 +02:00
-------------
2011-06-27 19:09:09 +02:00
2011-12-06 16:49:39 +01:00
All actors are supervised, i.e. linked to another actor with a fault
handling strategy. Actors will be restarted in case an exception is thrown while
processing a message. This restart involves the hooks mentioned above:
2011-06-27 19:09:09 +02:00
1. The old actor is informed by calling :meth: `preRestart` with the exception
2011-06-27 22:20:09 +02:00
which caused the restart and the message which triggered that exception; the
latter may be `` None `` if the restart was not caused by processing a
message, e.g. when a supervisor does not trap the exception and is restarted
in turn by its supervisor. This method is the best place for cleaning up,
2011-06-27 19:09:09 +02:00
preparing hand-over to the fresh actor instance, etc.
2011-12-14 19:25:32 +01:00
By default it stops all children and calls :meth: `postStop` .
2011-12-06 16:49:39 +01:00
2. The initial factory from the `` actorOf `` call is used
2011-09-26 11:08:45 +02:00
to produce the fresh instance.
2011-12-06 16:49:39 +01:00
3. The new actor’ s :meth: `postRestart` method is invoked with the exception
which caused the restart. By default the :meth: `preStart`
is called, just as in the normal start-up case.
2011-06-27 19:09:09 +02:00
An actor restart replaces only the actual actor object; the contents of the
2012-01-23 18:08:00 +01:00
mailbox is unaffected by the restart, so processing of messages will resume
after the :meth: `postRestart` hook returns. The message
2011-12-06 16:49:39 +01:00
that triggered the exception will not be received again. Any message
2011-06-27 22:20:09 +02:00
sent to an actor while it is being restarted will be queued to its mailbox as
2011-06-27 19:09:09 +02:00
usual.
2011-09-21 23:41:52 +02:00
2011-06-27 19:09:09 +02:00
Stop Hook
2011-10-05 17:41:00 +02:00
---------
2011-06-27 19:09:09 +02:00
After stopping an actor, its :meth: `postStop` hook is called, which may be used
e.g. for deregistering this actor from other services. This hook is guaranteed
2011-12-13 14:09:40 +01:00
to run after message queuing has been disabled for this actor, i.e. messages
sent to a stopped actor will be redirected to the :obj: `deadLetters` of the
:obj: `ActorSystem` .
2011-06-27 19:09:09 +02:00
2011-10-05 17:41:00 +02:00
Identifying Actors
==================
2011-04-09 19:55:46 -06:00
2011-12-15 23:48:35 +01:00
As described in :ref: `addressing` , each actor has a unique logical path, which
is obtained by following the chain of actors from child to parent until
reaching the root of the actor system, and it has a physical path, which may
differ if the supervision chain includes any remote supervisors. These paths
are used by the system to look up actors, e.g. when a remote message is
received and the recipient is searched, but they are also useful more directly:
actors may look up other actors by specifying absolute or relative
paths—logical or physical—and receive back an :class: `ActorRef` with the
result::
context.actorFor("/user/serviceA/aggregator") // will look up this absolute path
context.actorFor("../joe") // will look up sibling beneath same supervisor
2011-12-23 22:41:48 +01:00
The supplied path is parsed as a :class: `java.net.URI` , which basically means
that it is split on `` / `` into path elements. If the path starts with `` / `` , it
is absolute and the look-up starts at the root guardian (which is the parent of
`` "/user" `` ); otherwise it starts at the current actor. If a path element equals
`` .. `` , the look-up will take a step “up” towards the supervisor of the
currently traversed actor, otherwise it will step “down” to the named child.
2011-12-15 23:48:35 +01:00
It should be noted that the `` .. `` in actor paths here always means the logical
2011-12-23 22:41:48 +01:00
structure, i.e. the supervisor.
2012-01-23 17:56:52 +01:00
If the path being looked up does not exist, a special actor reference is
returned which behaves like the actor system’ s dead letter queue but retains
its identity (i.e. the path which was looked up).
2011-12-23 22:41:48 +01:00
Remote actor addresses may also be looked up, if remoting is enabled::
2011-12-15 23:48:35 +01:00
context.actorFor("akka://app@otherhost:1234/user/serviceB")
These look-ups return a (possibly remote) actor reference immediately, so you
will have to send to it and await a reply in order to verify that `` serviceB ``
2011-12-26 18:39:42 +01:00
is actually reachable and running. An example demonstrating actor look-up is
2011-12-28 19:09:08 +01:00
given in :ref: `remote-lookup-sample-scala` .
2011-04-09 19:55:46 -06:00
Messages and immutability
2011-10-05 17:41:00 +02:00
=========================
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
**IMPORTANT** : Messages can be any kind of object but have to be
immutable. Scala can’ t enforce immutability (yet) so this has to be by
convention. Primitives like String, Int, Boolean are always immutable. Apart
from these the recommended approach is to use Scala case classes which are
immutable (if you don’ t explicitly expose the state) and works great with
pattern matching at the receiver side.
2011-04-09 19:55:46 -06:00
Here is an example:
.. code-block :: scala
// define the case class
case class Register(user: User)
// create a new case class message
val message = Register(user)
2011-10-05 17:41:00 +02:00
Other good messages types are `` scala.Tuple2 `` , `` scala.List `` , `` scala.Map ``
which are all immutable and great for pattern matching.
2011-04-09 19:55:46 -06:00
Send messages
2011-10-05 17:41:00 +02:00
=============
2011-04-09 19:55:46 -06:00
2011-05-23 20:12:05 +02:00
Messages are sent to an Actor through one of the following methods.
2011-04-11 21:12:44 -06:00
2011-05-23 20:12:05 +02:00
* `` ! `` means “fire-and-forget”, e.g. send a message asynchronously and return
2012-01-20 18:09:26 +01:00
immediately. Also known as `` tell `` .
2011-05-23 20:12:05 +02:00
* `` ? `` sends a message asynchronously and returns a :class: `Future`
2012-01-20 18:09:26 +01:00
representing a possible reply. Also known as `` ask `` .
2011-04-09 19:55:46 -06:00
2011-09-21 23:41:52 +02:00
Message ordering is guaranteed on a per-sender basis.
2012-03-16 13:53:32 +01:00
.. note ::
There are performance implications of using `` ask `` since something needs to
keep track of when it times out, there needs to be something that bridges
a `` Promise `` into an `` ActorRef `` and it also needs to be reachable through
remoting. So always prefer `` tell `` for performance, and only `` ask `` if you must.
2011-12-08 14:06:20 +01:00
Tell: Fire-forget
-----------------
2011-04-09 19:55:46 -06:00
2011-05-23 20:12:05 +02:00
This is the preferred way of sending messages. No blocking waiting for a
message. This gives the best concurrency and scalability characteristics.
2011-04-09 19:55:46 -06:00
.. code-block :: scala
2011-10-05 17:41:00 +02:00
actor ! "hello"
2011-04-09 19:55:46 -06:00
2011-05-23 20:12:05 +02:00
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
2011-12-06 16:49:39 +01:00
in its `` sender: ActorRef `` member field. The target actor can use this
to reply to the original sender, by using `` sender ! replyMsg `` .
2011-04-09 19:55:46 -06:00
2011-12-13 14:09:40 +01:00
If invoked from an instance that is **not** an Actor the sender will be
2011-12-07 16:44:52 +01:00
:obj: `deadLetters` actor reference by default.
2011-04-09 19:55:46 -06:00
2011-12-08 14:06:20 +01:00
Ask: Send-And-Receive-Future
----------------------------
2011-04-09 19:55:46 -06:00
2012-01-20 18:09:26 +01:00
The `` ask `` pattern involves actors as well as futures, hence it is offered as
a use pattern rather than a method on :class: `ActorRef` :
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#ask-pipeTo
2011-04-09 19:55:46 -06:00
2012-01-20 18:09:26 +01:00
This example demonstrates `` ask `` together with the `` pipeTo `` pattern on
futures, because this is likely to be a common combination. Please note that
all of the above is completely non-blocking and asynchronous: `` ask `` produces
a :class: `Future` , three of which are composed into a new future using the
for-comprehension and then `` pipeTo `` installs an `` onComplete `` -handler on the
future to effect the submission of the aggregated :class: `Result` to another
actor.
2011-04-09 19:55:46 -06:00
2012-01-20 18:09:26 +01:00
Using `` ask `` will send a message to the receiving Actor as with `` tell `` , and
the receiving actor must reply with `` sender ! reply `` in order to complete the
returned :class: `Future` with a value. The `` ask `` operation involves creating
an internal actor for handling this reply, which needs to have a timeout after
which it is destroyed in order not to leak resources; see more below.
2011-12-06 16:49:39 +01:00
2011-12-13 14:09:40 +01:00
To complete the future with an exception you need send a Failure message to the sender.
2012-01-20 18:09:26 +01:00
This is *not done automatically* when an actor throws an exception while processing a
2011-12-13 14:09:40 +01:00
message.
2011-12-07 16:44:52 +01:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#reply-exception
2011-12-06 16:49:39 +01:00
2012-01-20 18:09:26 +01:00
If the actor does not complete the future, it will expire after the timeout
period, completing it with an :class: `AskTimeoutException` . The timeout is
taken from one of the following locations in order of precedence:
2011-04-09 19:55:46 -06:00
2011-12-20 08:12:20 +01:00
1. explicitly given timeout as in:
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#using-explicit-timeout
2011-12-13 14:09:40 +01:00
2011-12-20 08:12:20 +01:00
2. implicit argument of type :class: `akka.util.Timeout` , e.g.
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#using-implicit-timeout
2011-04-09 19:55:46 -06:00
2011-05-23 20:12:05 +02:00
See :ref: `futures-scala` for more information on how to await or query a
future.
2011-04-09 19:55:46 -06:00
2012-05-30 23:32:22 +02:00
The `` onComplete `` , `` onSuccess `` , or `` onFailure `` methods of the `` Future `` can be
2011-12-13 14:09:40 +01:00
used to register a callback to get a notification when the Future completes.
2011-12-08 14:06:20 +01:00
Gives you a way to avoid blocking.
2011-12-07 16:44:52 +01:00
.. warning ::
2011-12-12 20:09:26 +01:00
When using future callbacks, such as `` onComplete `` , `` onSuccess `` , and `` onFailure `` ,
2011-12-14 17:26:18 +01:00
inside actors you need to carefully avoid closing over
2011-12-13 14:09:40 +01:00
the containing actor’ s reference, i.e. do not call methods or access mutable state
on the enclosing actor from within the callback. This would break the actor
encapsulation and may introduce synchronization bugs and race conditions because
2011-12-09 12:29:24 +01:00
the callback will be scheduled concurrently to the enclosing actor. Unfortunately
2011-12-07 16:44:52 +01:00
there is not yet a way to detect these illegal accesses at compile time.
2011-12-08 14:06:20 +01:00
See also: :ref: `jmm-shared-state`
2011-04-09 19:55:46 -06:00
Forward message
2011-10-05 17:41:00 +02:00
---------------
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
You can forward a message from one actor to another. This means that the
original sender address/reference is maintained even though the message is going
through a 'mediator'. This can be useful when writing actors that work as
routers, load-balancers, replicators etc.
2011-04-09 19:55:46 -06:00
.. code-block :: scala
2011-12-08 14:06:20 +01:00
myActor.forward(message)
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
2011-04-09 19:55:46 -06:00
Receive messages
2011-10-05 17:41:00 +02:00
================
2011-04-09 19:55:46 -06:00
2011-04-11 21:12:44 -06:00
An Actor has to implement the `` receive `` method to receive messages:
2011-04-09 19:55:46 -06:00
.. code-block :: scala
2012-05-21 13:47:48 +02:00
def receive: PartialFunction[Any, Unit]
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
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.
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
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:
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala
2011-12-06 16:49:39 +01:00
:include: imports1,my-actor
2011-04-09 19:55:46 -06:00
2011-12-06 16:49:39 +01:00
.. _Actor.Reply:
2011-10-05 17:41:00 +02:00
2011-04-09 19:55:46 -06:00
Reply to messages
2011-10-05 17:41:00 +02:00
=================
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
If you want to have a handle for replying to a message, you can use
2011-11-09 11:10:36 +01:00
`` sender `` , which gives you an ActorRef. You can reply by sending to
2011-12-08 14:06:20 +01:00
that ActorRef with `` sender ! replyMsg `` . You can also store the ActorRef
2011-10-05 17:41:00 +02:00
for replying later, or passing on to other actors. If there is no sender (a
2011-11-09 11:10:36 +01:00
message was sent without an actor or future context) then the sender
2011-10-05 17:41:00 +02:00
defaults to a 'dead-letter' actor ref.
2011-05-08 16:59:17 +02:00
.. code-block :: scala
case request =>
2011-12-08 14:06:20 +01:00
val result = process(request)
sender ! result // will have dead-letter actor as default
2011-04-09 19:55:46 -06:00
Initial receive timeout
2011-10-05 17:41:00 +02:00
=======================
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
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.
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#receive-timeout
2011-04-09 19:55:46 -06:00
2011-12-30 00:00:25 +01:00
.. _stopping-actors-scala:
2011-10-05 17:41:00 +02:00
2011-04-09 19:55:46 -06:00
Stopping actors
2011-10-05 17:41:00 +02:00
===============
2011-04-09 19:55:46 -06:00
2011-12-14 20:26:27 +01:00
Actors are stopped by invoking the :meth: `stop` method of a `` ActorRefFactory `` ,
i.e. `` ActorContext `` or `` ActorSystem `` . Typically the context is used for stopping
2011-12-14 20:40:01 +01:00
child actors and the system for stopping top level actors. The actual termination of
the actor is performed asynchronously, i.e. :meth: `stop` may return before the actor is
stopped.
2011-04-09 19:55:46 -06:00
2011-12-13 14:09:40 +01:00
Processing of the current message, if any, will continue before the actor is stopped,
2011-12-07 16:44:52 +01:00
but additional messages in the mailbox will not be processed. By default these
2011-12-13 14:09:40 +01:00
messages are sent to the :obj: `deadLetters` of the :obj: `ActorSystem` , but that
2011-12-07 16:44:52 +01:00
depends on the mailbox implementation.
2011-12-06 16:49:39 +01:00
2011-12-28 13:09:56 +01:00
Termination of an actor proceeds in two steps: first the actor suspends its
mailbox processing and sends a stop command to all its children, then it keeps
processing the termination messages from its children until the last one is
gone, finally terminating itself (invoking :meth: `postStop` , dumping mailbox,
publishing :class: `Terminated` on the :ref: `DeathWatch <deathwatch-scala>` , telling
its supervisor). This procedure ensures that actor system sub-trees terminate
in an orderly fashion, propagating the stop command to the leaves and
collecting their confirmation back to the stopped supervisor. If one of the
actors does not respond (i.e. processing a message for extended periods of time
and therefore not receiving the stop command), this whole process will be
stuck.
Upon :meth: `ActorSystem.shutdown()` , the system guardian actors will be
stopped, and the aforementioned process will ensure proper termination of the
whole system.
The :meth: `postStop()` hook is invoked after an actor is fully stopped. This
enables cleaning up of resources:
2011-04-09 19:55:46 -06:00
.. code-block :: scala
2011-04-26 20:31:08 +02:00
override def postStop() = {
2011-12-28 13:09:56 +01:00
// close some file or database connection
2011-04-09 19:55:46 -06:00
}
2012-03-01 17:36:05 +01:00
.. note ::
Since stopping an actor is asynchronous, you cannot immediately reuse the
name of the child you just stopped; this will result in an
:class: `InvalidActorNameException` . Instead, :meth: `watch()` the terminating
actor and create its replacement in response to the :class: `Terminated`
message which will eventually arrive.
2011-04-09 19:55:46 -06:00
PoisonPill
2011-12-08 14:06:20 +01:00
----------
2011-10-05 17:41:00 +02:00
You can also send an actor the `` akka.actor.PoisonPill `` message, which will
2011-12-06 16:49:39 +01:00
stop the actor when the message is processed. `` PoisonPill `` is enqueued as
ordinary messages and will be handled after messages that were already queued
in the mailbox.
2011-04-09 19:55:46 -06:00
2012-01-03 11:41:49 +01:00
Graceful Stop
-------------
:meth: `gracefulStop` is useful if you need to wait for termination or compose ordered
termination of several actors:
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#gracefulStop
2012-01-03 11:41:49 +01:00
2012-05-16 13:43:00 +02:00
When `` gracefulStop() `` returns successfully, the actor’ s `` postStop() `` hook
will have been executed: there exists a happens-before edge between the end of
`` postStop() `` and the return of `` gracefulStop() `` .
.. warning ::
Keep in mind that an actor stopping and its name being deregistered are
separate events which happen asynchronously from each other. Therefore it may
be that you will find the name still in use after `` gracefulStop() ``
returned. In order to guarantee proper deregistration, only reuse names from
within a supervisor you control and only in response to a :class: `Terminated`
message, i.e. not for top-level actors.
2012-01-03 11:41:49 +01:00
2011-06-27 19:09:09 +02:00
.. _Actor.HotSwap:
2011-12-08 14:44:18 +01:00
Become/Unbecome
===============
2011-04-09 19:55:46 -06:00
Upgrade
2011-10-05 17:41:00 +02:00
-------
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
Akka supports hotswapping the Actor’ s message loop (e.g. its implementation) at
2011-12-08 14:06:20 +01:00
runtime: Invoke the `` context.become `` method from within the Actor.
2011-04-11 21:12:44 -06:00
2011-12-08 14:44:18 +01:00
Become takes a `` PartialFunction[Any, Unit] `` that implements
2011-10-05 17:41:00 +02:00
the new message handler. The hotswapped code is kept in a Stack which can be
pushed and popped.
2011-04-09 19:55:46 -06:00
2011-12-07 13:30:56 +01:00
.. warning ::
Please note that the actor will revert to its original behavior when restarted by its Supervisor.
2011-12-08 14:44:18 +01:00
To hotswap the Actor behavior using `` become `` :
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#hot-swap-actor
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
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`_ .
2012-03-05 10:27:00 +01:00
.. _Dining Hakkers: http://github.com/akka/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnBecome.scala
2011-04-09 19:55:46 -06:00
2011-04-11 21:12:44 -06:00
Here is another little cute example of `` become `` and `` unbecome `` in action:
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#swapper
2011-10-05 17:41:00 +02:00
Encoding Scala Actors nested receives without accidentally leaking memory
-------------------------------------------------------------------------
2012-05-24 22:23:36 +02:00
See this `Unnested receive example <https://github.com/akka/akka/blob/master/akka-docs/scala/code/docs/actor/UnnestedReceives.scala> `_ .
2011-10-05 17:41:00 +02:00
2011-04-09 19:55:46 -06:00
Downgrade
2011-10-05 17:41:00 +02:00
---------
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
Since the hotswapped code is pushed to a Stack you can downgrade the code as
2011-12-08 14:06:20 +01:00
well, all you need to do is to: Invoke the `` context.unbecome `` method from within the Actor.
2011-04-09 19:55:46 -06:00
2011-12-08 14:44:18 +01:00
This will pop the Stack and replace the Actor's implementation with the
2011-10-05 17:41:00 +02:00
`` PartialFunction[Any, Unit] `` that is at the top of the Stack.
2011-04-09 19:55:46 -06:00
2011-12-08 14:44:18 +01:00
Here's how you use the `` unbecome `` method:
2011-04-09 19:55:46 -06:00
.. code-block :: scala
2011-12-06 16:49:39 +01:00
def receive = {
2011-12-08 14:06:20 +01:00
case "revert" => context.unbecome()
2011-04-09 19:55:46 -06:00
}
2011-10-05 17:41:00 +02:00
2011-04-09 19:55:46 -06:00
Killing an Actor
2011-10-05 17:41:00 +02:00
================
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
You can kill an actor by sending a `` Kill `` message. This will restart the actor
through regular supervisor semantics.
2011-04-09 19:55:46 -06:00
Use it like this:
.. code-block :: scala
// kill the actor called 'victim'
victim ! Kill
2011-07-15 08:54:44 +03:00
Actors and exceptions
2011-10-05 17:41:00 +02:00
=====================
It can happen that while a message is being processed by an actor, that some
kind of exception is thrown, e.g. a database exception.
2011-07-15 08:54:44 +03:00
What happens to the Message
2011-10-05 17:41:00 +02:00
---------------------------
2011-07-15 08:41:42 +03:00
2011-10-05 17:41:00 +02:00
If an exception is thrown while a message is being processed (so taken of his
2012-06-04 23:35:52 +02:00
mailbox and handed over to the receive), then this message will be lost. It is
2011-10-05 17:41:00 +02:00
important to understand that it is not put back on the mailbox. So if you want
to retry processing of a message, you need to deal with it yourself by catching
the exception and retry your flow. Make sure that you put a bound on the number
of retries since you don't want a system to livelock (so consuming a lot of cpu
cycles without making progress).
2011-07-15 08:41:42 +03:00
2011-07-15 08:54:44 +03:00
What happens to the mailbox
2011-10-05 17:41:00 +02:00
---------------------------
If an exception is thrown while a message is being processed, nothing happens to
the mailbox. If the actor is restarted, the same mailbox will be there. So all
messages on that mailbox, will be there as well.
2011-07-15 08:54:44 +03:00
What happens to the actor
2011-10-05 17:41:00 +02:00
-------------------------
2011-12-13 14:09:40 +01:00
If an exception is thrown, the actor instance is discarded and a new instance is
2011-12-07 16:44:52 +01:00
created. This new instance will now be used in the actor references to this actor
2011-12-13 14:09:40 +01:00
(so this is done invisible to the developer). Note that this means that current
state of the failing actor instance is lost if you don't store and restore it in
`` preRestart `` and `` postRestart `` callbacks.
2011-07-15 08:54:44 +03:00
2011-04-09 19:55:46 -06:00
Extending Actors using PartialFunction chaining
2011-10-05 17:41:00 +02:00
===============================================
2011-04-09 19:55:46 -06:00
2011-10-05 17:41:00 +02:00
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.
2011-04-09 19:55:46 -06:00
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#receive-orElse
2012-02-01 11:46:46 +01:00
Or:
2012-05-24 22:23:36 +02:00
.. includecode :: code/docs/actor/ActorDocSpec.scala#receive-orElse2