Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Actor base class that should be extended to create Java actors that use lambdas.
Example:
public class MyActor extends AbstractActor { int count = 0; public MyActor() { receive(receiveBuilder() .match(Double.class, d -> { sender().tell(d.isNaN() ? 0 : d, self()); }) .match(Integer.class, i -> { sender().tell(i * 10, self()); }) .match(String.class, s -> s.startsWith("foo"), s -> { sender().tell(s.toUpperCase(), self()); }) .build(); ); } }
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Actor base class that should be extended to create an actor with a stash.
The stash enables an actor to temporarily stash away messages that can not or should not be handled using the actor's current behavior.
Example:
public class MyActorWithStash extends AbstractActorWithStash { int count = 0; public MyActorWithStash() { receive(ReceiveBuilder. match(String.class, s -> { if (count < 0) { sender().tell(new Integer(s.length()), self()); } else if (count == 2) { count = -1; unstashAll(); } else { count += 1; stash(); }}).build() ); } }Note that the subclasses of
AbstractActorWithStash
by default request a Deque based mailbox since this class
implements the RequiresMessageQueue<DequeBasedMessageQueueSemantics>
marker interface.
You can override the default mailbox provided when DequeBasedMessageQueueSemantics
are requested via config:
akka.actor.mailbox.requirements { "akka.dispatch.BoundedDequeBasedMessageQueueSemantics" = your-custom-mailbox }Alternatively, you can add your own requirement marker to the actor and configure a mailbox type to be used for your marker.
For a Stash
based actor that enforces unbounded deques see akka.actor.AbstractActorWithUnboundedStash.
There is also an unrestricted version akka.actor.AbstractActorWithUnrestrictedStash that does not
enforce the mailbox type.
Java API: Support for scheduled self
messages via TimerScheduler.
Java API: Support for scheduled self
messages via TimerScheduler.
Timers are bound to the lifecycle of the actor that owns it, and thus are cancelled automatically when it is restarted or stopped.
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Actor base class with Stash
that enforces an unbounded deque for the actor. The proper mailbox has to be configured
manually, and the mailbox should extend the akka.dispatch.DequeBasedMessageQueueSemantics marker trait.
See akka.actor.AbstractActorWithStash for details on how Stash
works.
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Actor base class with Stash
that does not enforce any mailbox type. The mailbox of the actor has to be configured
manually. See akka.actor.AbstractActorWithStash for details on how Stash
works.
Java API for ExtensionId
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Finite State Machine actor abstract base class.
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Finite State Machine actor abstract base class with Stash support.
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Actor base class that mixes in logging into the Actor.
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Finite State Machine actor abstract base class.
Actor base trait that should be extended by or mixed to create an Actor with the semantics of the 'Actor Model': http://en.wikipedia.org/wiki/Actor_model
Actor base trait that should be extended by or mixed to create an Actor with the semantics of the 'Actor Model': http://en.wikipedia.org/wiki/Actor_model
An actor has a well-defined (non-cyclic) life-cycle.
The Actor's own akka.actor.ActorRef is available as self
, the current
message’s sender as sender()
and the akka.actor.ActorContext as
context
. The only abstract method is receive
which shall return the
initial behavior of the actor as a partial function (behavior can be changed
using context.become
and context.unbecome
).
This is the Scala API (hence the Scala code below), for the Java API see akka.actor.AbstractActor.
class ExampleActor extends Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { case _: ArithmeticException => Resume case _: NullPointerException => Restart case _: IllegalArgumentException => Stop case _: Exception => Escalate } def receive = { // directly calculated reply case Request(r) => sender() ! calculate(r) // just to demonstrate how to stop yourself case Shutdown => context.stop(self) // error kernel with child replying directly to 'sender()' case Dangerous(r) => context.actorOf(Props[ReplyToOriginWorker]).tell(PerformWork(r), sender()) // error kernel with reply going through us case OtherJob(r) => context.actorOf(Props[ReplyToMeWorker]) ! JobRequest(r, sender()) case JobReply(result, orig_s) => orig_s ! result } }
The last line demonstrates the essence of the error kernel design: spawn
one-off actors which terminate after doing their job, pass on sender()
to
allow direct reply if that is what makes sense, or round-trip the sender
as shown with the fictitious JobRequest/JobReply message pair.
If you don’t like writing context
you can always import context._
to get
direct access to actorOf
, stop
etc. This is not default in order to keep
the name-space clean.
The actor context - the view of the actor cell from the actor.
The actor context - the view of the actor cell from the actor. Exposes contextual information for the actor and the current message.
There are several possibilities for creating actors (see akka.actor.Props
for details on props
):
// Java or Scala context.actorOf(props, "name") context.actorOf(props) // Scala context.actorOf(Props[MyActor]) context.actorOf(Props(classOf[MyActor], arg1, arg2), "name") // Java getContext().actorOf(Props.create(MyActor.class)); getContext().actorOf(Props.create(MyActor.class, arg1, arg2), "name");
Where no name is given explicitly, one will be automatically generated.
Reply to akka.actor.Identify.
Reply to akka.actor.Identify. Contains
Some(ref)
with the ActorRef
of the actor replying to the request or
None
if no actor matched the request.
The correlationId
is taken from the messageId
in
the Identify
message.
An ActorInitializationException is thrown when the initialization logic for an Actor fails.
An ActorInitializationException is thrown when the initialization logic for an Actor fails.
There is an extractor which works for ActorInitializationException and its subtypes:
ex match { case ActorInitializationException(actor, message, cause) => ... }
When an InterruptedException is thrown inside an Actor, it is wrapped as an ActorInterruptedException as to avoid cascading interrupts to other threads than the originally interrupted one.
When an InterruptedException is thrown inside an Actor, it is wrapped as an ActorInterruptedException as to avoid cascading interrupts to other threads than the originally interrupted one.
ActorKilledException is thrown when an Actor receives the akka.actor.Kill message
ActorKilledException is thrown when an Actor receives the akka.actor.Kill message
Scala API: Mix in ActorLogging into your Actor to easily obtain a reference to a logger, which is available under the name "log".
Scala API: Mix in ActorLogging into your Actor to easily obtain a reference to a logger, which is available under the name "log".
class MyActor extends Actor with ActorLogging { def receive = { case "pigdog" => log.info("We've got yet another pigdog on our hands") } }
When ActorSelection#resolveOne can't identify the actor the
Future
is completed with this failure.
When ActorSelection#resolveOne can't identify the actor the
Future
is completed with this failure.
Actor path is a unique path to an actor that shows the creation path up through the actor tree to the root actor.
Actor path is a unique path to an actor that shows the creation path up through the actor tree to the root actor.
ActorPath defines a natural ordering (so that ActorRefs can be put into collections with this requirement); this ordering is intended to be as fast as possible, which owing to the bottom-up recursive nature of ActorPath is sorted by path elements FROM RIGHT TO LEFT, where RootActorPath > ChildActorPath in case the number of elements is different.
Two actor paths are compared equal when they have the same name and parent elements, including the root address information. That does not necessarily mean that they point to the same incarnation of the actor if the actor is re-created with the same path. In other words, in contrast to how actor references are compared the unique id of the actor is not taken into account when comparing actor paths.
Immutable and serializable handle to an actor, which may or may not reside on the local host or inside the same akka.actor.ActorSystem.
Immutable and serializable handle to an actor, which may or may not reside on the local host or inside the same akka.actor.ActorSystem. An ActorRef can be obtained from an akka.actor.ActorRefFactory, an interface which is implemented by ActorSystem and akka.actor.ActorContext. This means actors can be created top-level in the ActorSystem or as children of an existing actor, but only from within that actor.
ActorRefs can be freely shared among actors by message passing. Message passing conversely is their only purpose, as demonstrated in the following examples:
Scala:
import akka.pattern.ask import scala.concurrent.Await class ExampleActor extends Actor { val other = context.actorOf(Props[OtherActor], "childName") // will be destroyed and re-created upon restart by default def receive { case Request1(msg) => other ! refine(msg) // uses this actor as sender reference, reply goes to us case Request2(msg) => other.tell(msg, sender()) // forward sender reference, enabling direct reply case Request3(msg) => implicit val timeout = Timeout(5.seconds) (other ? msg) pipeTo sender() // the ask call will get a future from other's reply // when the future is complete, send its value to the original sender } }
Java:
import static akka.pattern.Patterns.ask; import static akka.pattern.Patterns.pipe; public class ExampleActor extends AbstractActor { // this child will be destroyed and re-created upon restart by default final ActorRef other = getContext().actorOf(Props.create(OtherActor.class), "childName"); @Override public Receive createReceive() { return receiveBuilder() .match(Request1.class, msg -> // uses this actor as sender reference, reply goes to us other.tell(msg, getSelf())) .match(Request2.class, msg -> // forward sender reference, enabling direct reply other.tell(msg, getSender())) .match(Request3.class, msg -> // the ask call will get a future from other's reply // when the future is complete, send its value to the original sender pipe(ask(other, msg, 5000), context().dispatcher()).to(getSender())) .build(); } }
ActorRef does not have a method for terminating the actor it points to, use
akka.actor.ActorRefFactory.stop(ref)
, or send a akka.actor.PoisonPill,
for this purpose.
Two actor references are compared equal when they have the same path and point to the same actor incarnation. A reference pointing to a terminated actor doesn't compare equal to a reference pointing to another (re-created) actor with the same path.
If you need to keep track of actor references in a collection and do not care
about the exact actor incarnation you can use the
as key because
the unique id of the actor is not taken into account when comparing actor paths.
ActorPath
Interface implemented by ActorSystem and ActorContext, the only two places from which you can get fresh actors.
Interface implemented by ActorSystem and ActorContext, the only two places from which you can get fresh actors.
Interface for all ActorRef providers to implement.
An ActorSelection is a logical view of a section of an ActorSystem's tree of Actors, allowing for broadcasting of messages to that section.
An ActorSelection is a logical view of a section of an ActorSystem's tree of Actors, allowing for broadcasting of messages to that section.
An actor system is a hierarchical group of actors which share common configuration, e.g.
An actor system is a hierarchical group of actors which share common configuration, e.g. dispatchers, deployments, remote capabilities and addresses. It is also the entry point for creating or looking up actors.
There are several possibilities for creating actors (see akka.actor.Props
for details on props
):
// Java or Scala system.actorOf(props, "name") system.actorOf(props) // Scala system.actorOf(Props[MyActor], "name") system.actorOf(Props(classOf[MyActor], arg1, arg2), "name") // Java system.actorOf(Props.create(MyActor.class), "name"); system.actorOf(Props.create(MyActor.class, arg1, arg2), "name");
Where no name is given explicitly, one will be automatically generated.
Important Notice:
This class is not meant to be extended by user code. If you want to actually roll your own Akka, it will probably be better to look into extending akka.actor.ExtendedActorSystem instead, but beware that you are completely on your own in that case!
The address specifies the physical location under which an Actor can be reached.
The address specifies the physical location under which an Actor can be reached. Examples are local addresses, identified by the ActorSystem’s name, and remote addresses, identified by protocol, host and port.
This class is final to allow use as a case class (copy method etc.); if for example a remote transport would want to associate additional information with an address, then this must be done externally.
Subscribe to this class to be notified about all DeadLetters (also the suppressed ones).
Applies the fault handling Directive
(Resume, Restart, Stop) specified in the Decider
to all children when one fails, as opposed to akka.actor.OneForOneStrategy that applies
it only to the child actor that failed.
Applies the fault handling Directive
(Resume, Restart, Stop) specified in the Decider
to all children when one fails, as opposed to akka.actor.OneForOneStrategy that applies
it only to the child actor that failed.
the number of times a child actor is allowed to be restarted, negative value means no limit, if the limit is exceeded the child actor is stopped
duration of the time window for maxNrOfRetries, Duration.Inf means no window
the strategy logs the failure if this is enabled (true), by default it is enabled
mapping from Throwable to akka.actor.SupervisorStrategy.Directive, you can also use a scala.collection.immutable.Seq of Throwables which maps the given Throwables to restarts, otherwise escalates.
Core bootstrap settings of the actor system, create using one of the factories in BootstrapSetup, constructor is *Internal API*.
Signifies something that can be cancelled There is no strict guarantee that the implementation is thread-safe, but it should be good practice to make it so.
ChildRestartStats is the statistics kept by every parent Actor for every child Actor and is used for SupervisorStrategies to know how to deal with problems that occur for the children.
ContextualTypedActorFactory allows TypedActors to create children, effectively forming the same Actor Supervision Hierarchies as normal Actors can.
When a message is sent to an Actor that is terminated before receiving the message, it will be sent as a DeadLetter to the ActorSystem's EventStream.
When a message is sent to an Actor that is terminated before receiving the message, it will be sent as a DeadLetter to the ActorSystem's EventStream.
When this message was sent without a sender ActorRef, sender
will be system.deadLetters
.
Use with caution: Messages extending this trait will not be logged by the default dead-letters listener.
Use with caution: Messages extending this trait will not be logged by the default dead-letters listener. Instead they will be wrapped as SuppressedDeadLetter and may be subscribed for explicitly.
A DeathPactException is thrown by an Actor that receives a Terminated(someActor) message that it doesn't handle itself, effectively crashing the Actor and escalating to the supervisor.
A DeathPactException is thrown by an Actor that receives a Terminated(someActor) message that it doesn't handle itself, effectively crashing the Actor and escalating to the supervisor.
This class represents deployment configuration for a given actor path.
This class represents deployment configuration for a given actor path. It is marked final in order to guarantee stable merge semantics (i.e. what overrides what in case multiple configuration sources are available) and is fully extensible via its Scope argument, and by the fact that an arbitrary Config section can be passed along with it (which will be merged when merging two Deploys).
The path field is used only when inserting the Deploy into a deployer and not needed when just doing deploy-as-you-go:
val remoteProps = someProps.withDeploy(Deploy(scope = RemoteScope("someOtherNodeName")))
Scala API: Mix in DiagnosticActorLogging into your Actor to easily obtain a reference to a logger with MDC support, which is available under the name "log".
Scala API: Mix in DiagnosticActorLogging into your Actor to easily obtain a reference to a logger with MDC support, which is available under the name "log". In the example bellow "the one who knocks" will be available under the key "iam" for using it in the logback pattern.
class MyActor extends Actor with DiagnosticActorLogging { override def mdc(currentMessage: Any): MDC = { Map("iam", "the one who knocks") } def receive = { case "pigdog" => log.info("We've got yet another pigdog on our hands") } }
The DynamicAccess implementation is the class which is used for loading all configurable parts of an actor system (the akka.actor.ReflectiveDynamicAccess is the default implementation).
The DynamicAccess implementation is the class which is used for loading all configurable parts of an actor system (the akka.actor.ReflectiveDynamicAccess is the default implementation).
This is an internal facility and users are not expected to encounter it unless they are extending Akka in ways which go beyond simple Extensions.
More powerful interface to the actor system’s implementation which is presented to extensions (see akka.actor.Extension).
More powerful interface to the actor system’s implementation which is presented to extensions (see akka.actor.Extension).
Important Notice:
This class is not meant to be extended by user code. If you want to actually roll your own Akka, beware that you are completely on your own in that case!
The basic ActorSystem covers all that is needed for locally running actors, using futures and so on.
The basic ActorSystem covers all that is needed for locally running actors,
using futures and so on. In addition, more features can hook into it and
thus become visible to actors et al by registering themselves as extensions.
This is accomplished by providing an extension—which is an object
implementing this trait—to ActorSystem.registerExtension(...)
or by
specifying the corresponding option in the configuration passed to
ActorSystem, which will then instantiate (without arguments) each FQCN and
register the result.
The extension itself can be created in any way desired and has full access to the ActorSystem implementation.
This trait is only a marker interface to signify an Akka Extension. This is how an extension is normally constructed.
Scala API:
object MyExt extends ExtensionId[Ext] with ExtensionIdProvider { override def lookup = MyExt override def createExtension(system: ExtendedActorSystem): Ext = new Ext(system) // Java API: retrieve the extension for the given system. override def get(system: ActorSystem): UdpExt = super.get(system) } class Ext(system: ExtendedActorSystem) extends Extension { ... }
Java API:
public class MyExt extends AbstractExtensionId<MyExtImpl> implements ExtensionIdProvider { public final static MyExt MyExtProvider = new MyExt(); private MyExt() {} public MyExt lookup() { return MyExt.MyExtProvider; } public MyExtImpl createExtension(ExtendedActorSystem system) { return new MyExtImpl(); } } public class MyExtImpl implements Extension { ... }
Identifies an Extension Lookup of Extensions is done by object identity, so the Id must be the same wherever it's used, otherwise you'll get the same extension loaded multiple times.
To be able to load an ExtensionId from the configuration, a class that implements ExtensionIdProvider must be specified.
To be able to load an ExtensionId from the configuration, a class that implements ExtensionIdProvider must be specified. The lookup method should return the canonical reference to the extension.
Finite State Machine actor trait.
Finite State Machine actor trait. Use as follows:
object A { trait State case class One extends State case class Two extends State case class Data(i : Int) } class A extends Actor with FSM[A.State, A.Data] { import A._ startWith(One, Data(42)) when(One) { case Event(SomeMsg, Data(x)) => ... case Event(SomeOtherMsg, _) => ... // when data not needed } when(Two, stateTimeout = 5 seconds) { ... } initialize() }
Within the partial function the following values are returned for effecting state transitions:
stay
for staying in the same statestay using Data(...)
for staying in the same state, but with
different datastay forMax 5.millis
for staying with a state timeout; can be
combined with using
goto(...)
for changing into a different state; also supports
using
and forMax
stop
for terminating this FSM actorEach of the above also supports the method replying(AnyRef)
for
sending a reply before changing state.
While changing state, custom handlers may be invoked which are registered
using onTransition
. This is meant to enable concentrating
different concerns in different places; you may choose to use
when
for describing the properties of a state, including of
course initiating transitions, but you can describe the transitions using
onTransition
to avoid having to duplicate that code among
multiple paths which lead to a transition:
onTransition { case Active -> _ => cancelTimer("activeTimer") }
Multiple such blocks are supported and all of them will be called, not only the first matching one.
Another feature is that other actors may subscribe for transition events by
sending a SubscribeTransitionCallback
message to this actor.
Stopping a listener without unregistering will not remove the listener from the
subscription list; use UnsubscribeTransitionCallback
before stopping
the listener.
State timeouts set an upper bound to the time which may pass before another message is received in the current state. If no external message is available, then upon expiry of the timeout a StateTimeout message is sent. Note that this message will only be received in the state for which the timeout was set and that any message received will cancel the timeout (possibly to be started again by the next transition).
Another feature is the ability to install and cancel single-shot as well as repeated timers which arrange for the sending of a user-specified message:
setTimer("tock", TockMsg, 1 second, true) // repeating setTimer("lifetime", TerminateMsg, 1 hour, false) // single-shot cancelTimer("tock") isTimerActive("tock")
A message all Actors will understand, that when processed will reply with
akka.actor.ActorIdentity containing the ActorRef
.
A message all Actors will understand, that when processed will reply with
akka.actor.ActorIdentity containing the ActorRef
. The messageId
is returned in the ActorIdentity
message as correlationId
.
IllegalActorStateException is thrown when a core invariant in the Actor implementation has been violated.
IllegalActorStateException is thrown when a core invariant in the Actor implementation has been violated. For instance, if you try to create an Actor that doesn't extend Actor.
An Inbox is an actor-like object which is interrogated from the outside.
An Inbox is an actor-like object which is interrogated from the outside. It contains an actor whose reference can be passed to other actors as usual and it can watch other actors’ lifecycle.
This interface defines a class of actor creation strategies deviating from the usual default of just reflectively instantiating the Actor subclass.
This interface defines a class of actor creation strategies deviating from the usual default of just reflectively instantiating the Actor subclass. It can be used to allow a dependency injection framework to determine the actual actor class and how it shall be instantiated.
An InvalidActorNameException is thrown when you try to convert something, usually a String, to an Actor name which doesn't validate.
An InvalidActorNameException is thrown when you try to convert something, usually a String, to an Actor name which doesn't validate.
InvalidMessageException is thrown when an invalid message is sent to an Actor;
Currently only null
is an invalid message.
InvalidMessageException is thrown when an invalid message is sent to an Actor;
Currently only null
is an invalid message.
This scheduler implementation is based on a revolving wheel of buckets, like Netty’s HashedWheelTimer, which it advances at a fixed tick rate and dispatches tasks it finds in the current bucket to their respective ExecutionContexts.
This scheduler implementation is based on a revolving wheel of buckets, like Netty’s HashedWheelTimer, which it advances at a fixed tick rate and dispatches tasks it finds in the current bucket to their respective ExecutionContexts. The tasks are held in TaskHolders, which upon cancellation null out their reference to the actual task, leaving only this shell to be cleaned up when the wheel reaches that bucket next time. This enables the use of a simple linked list to chain the TaskHolders off the wheel.
Also noteworthy is that this scheduler does not obtain a current time stamp when scheduling single-shot tasks, instead it always rounds up the task delay to a full multiple of the TickDuration. This means that tasks are scheduled possibly one tick later than they could be (if checking that “now() + delay <= nextTick” were done).
Stackable trait for akka.actor.FSM which adds a rolling event log and debug logging capabilities (analogous to akka.event.LoggingReceive).
Stackable trait for akka.actor.FSM which adds a rolling event log and debug logging capabilities (analogous to akka.event.LoggingReceive).
1.2
This is the default value and as such allows overrides.
This is the default value and as such allows overrides.
Marker trait to signal that this class should not be verified for serializability.
Marker trait to indicate that a message should not reset the receive timeout.
Applies the fault handling Directive
(Resume, Restart, Stop) specified in the Decider
to the child actor that failed, as opposed to akka.actor.AllForOneStrategy that applies
it to all children.
Applies the fault handling Directive
(Resume, Restart, Stop) specified in the Decider
to the child actor that failed, as opposed to akka.actor.AllForOneStrategy that applies
it to all children.
the number of times a child actor is allowed to be restarted, negative value means no limit, if the limit is exceeded the child actor is stopped
duration of the time window for maxNrOfRetries, Duration.Inf means no window
the strategy logs the failure if this is enabled (true), by default it is enabled
mapping from Throwable to akka.actor.SupervisorStrategy.Directive, you can also use a scala.collection.immutable.Seq of Throwables which maps the given Throwables to restarts, otherwise escalates.
Marker trait to indicate that a message might be potentially harmful, this is used to block messages coming in over remoting.
A PostRestartException is thrown when constructor or postRestart() method fails during a restart attempt.
A PostRestartException is thrown when constructor or postRestart() method fails during a restart attempt.
A PreRestartException is thrown when the preRestart() method failed; this exception is not propagated to the supervisor, as it originates from the already failed instance, hence it is only visible as log entry on the event stream.
A PreRestartException is thrown when the preRestart() method failed; this exception is not propagated to the supervisor, as it originates from the already failed instance, hence it is only visible as log entry on the event stream.
Props is a configuration object using in creating an Actor; it is immutable, so it is thread-safe and fully shareable.
Props is a configuration object using in creating an Actor; it is immutable, so it is thread-safe and fully shareable.
Examples on Scala API:
val props = Props.empty val props = Props[MyActor] val props = Props(classOf[MyActor], arg1, arg2) val otherProps = props.withDispatcher("dispatcher-id") val otherProps = props.withDeploy(<deployment info>)
Examples on Java API:
final Props props = Props.empty(); final Props props = Props.create(MyActor.class, arg1, arg2); final Props otherProps = props.withDispatcher("dispatcher-id"); final Props otherProps = props.withDeploy(<deployment info>);
This is the default akka.actor.DynamicAccess implementation used by akka.actor.ExtendedActorSystem unless overridden.
This is the default akka.actor.DynamicAccess implementation used by akka.actor.ExtendedActorSystem
unless overridden. It uses reflection to turn fully-qualified class names into Class[_]
objects
and creates instances from there using getDeclaredConstructor()
and invoking that. The class loader
to be used for all this is determined by the actor system’s class loader by default.
Root of the hierarchy of ActorPaths.
Root of the hierarchy of ActorPaths. There is exactly root per ActorSystem and node (for remote-enabled or clustered systems).
This trait represents the Scala Actor API There are implicit conversions in package.scala from ActorRef -> ScalaActorRef and back
Contains the Scala API (!-method) for ActorSelections) which provides automatic tracking of the sender, as per the usual implicit ActorRef pattern.
An Akka scheduler service.
An Akka scheduler service. This one needs one special behavior: if Closeable, it MUST execute all outstanding tasks upon .close() in order to properly shutdown all dispatchers.
Furthermore, this timer service MUST throw IllegalStateException if it cannot schedule a task. Once scheduled, the task MUST be executed. If executed upon close(), the task may execute before its timeout.
Scheduler implementation are loaded reflectively at ActorSystem start-up with the following constructor arguments: 1) the system’s com.typesafe.config.Config (from system.settings.config) 2) a akka.event.LoggingAdapter 3) a java.util.concurrent.ThreadFactory
Please note that this scheduler implementation is higly optimised for high-throughput
and high-frequency events. It is not to be confused with long-term schedulers such as
Quartz. The scheduler will throw an exception if attempts are made to schedule too far
into the future (which by default is around 8 months (Int.MaxValue
seconds).
The scope of a akka.actor.Deploy serves two purposes: as a marker for pattern matching the “scope” (i.e.
The scope of a akka.actor.Deploy serves two purposes: as a marker for pattern matching the “scope” (i.e. local/remote/cluster) as well as for extending the information carried by the final Deploy class. Scopes can be used in conjunction with a custom akka.actor.ActorRefProvider, making Akka actors fully extensible.
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.
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.
Example:
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() }, discardOld = false) case "done" ⇒ // done case msg ⇒ stash() } }
Note that the Stash
trait can only be used together with actors that have a deque-based
mailbox. By default Stash based actors request a Deque based mailbox since the stash
trait extends RequiresMessageQueue[DequeBasedMessageQueueSemantics]
.
You can override the default mailbox provided when DequeBasedMessageQueueSemantics
are requested via config:
akka.actor.mailbox.requirements { "akka.dispatch.BoundedDequeBasedMessageQueueSemantics" = your-custom-mailbox }Alternatively, you can add your own requirement marker to the actor and configure a mailbox type to be used for your marker.
For a Stash
that also enforces unboundedness of the deque see akka.actor.UnboundedStash. For a Stash
that does not enforce any mailbox type see akka.actor.UnrestrictedStash.
Note that the Stash
trait must be mixed into (a subclass of) the Actor
trait before
any trait/class that overrides the preRestart
callback. This means it's not possible to write
Actor with MyActor with Stash
if MyActor
overrides preRestart
.
Is thrown when the size of the Stash exceeds the capacity of the Stash
An Akka SupervisorStrategy is the policy to apply for crashing children.
An Akka SupervisorStrategy is the policy to apply for crashing children.
IMPORTANT:
You should not normally need to create new subclasses, instead use the existing akka.actor.OneForOneStrategy or akka.actor.AllForOneStrategy, but if you do, please read the docs of the methods below carefully, as incorrect implementations may lead to “blocked” actor systems (i.e. permanently suspended actors).
Implement this interface in order to configure the supervisorStrategy for
the top-level guardian actor (/user
).
Implement this interface in order to configure the supervisorStrategy for
the top-level guardian actor (/user
). An instance of this class must be
instantiable using a no-arg constructor.
Similar to DeadLetter with the slight twist of NOT being logged by the default dead letters listener.
Similar to DeadLetter with the slight twist of NOT being logged by the default dead letters listener. Messages which end up being suppressed dead letters are internal messages for which ending up as dead-letter is both expected and harmless.
It is possible to subscribe to suppressed dead letters on the ActorSystem's EventStream explicitly.
When Death Watch is used, the watcher will receive a Terminated(watched) message when watched is terminated.
When Death Watch is used, the watcher will receive a Terminated(watched) message when watched is terminated. Terminated message can't be forwarded to another actor, since that actor might not be watching the subject. Instead, if you need to forward Terminated to another actor you should send the information in your own message.
Support for scheduled self
messages in an actor.
Support for scheduled self
messages in an actor.
It is used by mixing in trait Timers
in Scala or extending AbstractActorWithTimers
in Java.
Timers are bound to the lifecycle of the actor that owns it, and thus are cancelled automatically when it is restarted or stopped.
TimerScheduler
is not thread-safe, i.e. it must only be used within
the actor that owns it.
Scala API: Mix in Timers into your Actor to get support for scheduled
self
messages via TimerScheduler.
Scala API: Mix in Timers into your Actor to get support for scheduled
self
messages via TimerScheduler.
Timers are bound to the lifecycle of the actor that owns it, and thus are cancelled automatically when it is restarted or stopped.
A TypedActorFactory is something that can created TypedActor instances.
TypedProps is a TypedActor configuration object, that is thread safe and fully sharable.
TypedProps is a TypedActor configuration object, that is thread safe and fully sharable. It's used in TypedActorFactory.typedActorOf to configure a TypedActor instance.
The UnboundedStash
trait is a version of akka.actor.Stash that enforces an unbounded stash for you actor.
This message is published to the EventStream whenever an Actor receives a message it doesn't understand
This message is published to the EventStream whenever an Actor receives a message it doesn't understand
A version of akka.actor.Stash that does not enforce any mailbox type.
A version of akka.actor.Stash that does not enforce any mailbox type. The proper mailbox has to be configured manually, and the mailbox should extend the akka.dispatch.DequeBasedMessageQueueSemantics marker trait.
If the validation of the ReceiveBuilder
match logic turns out to be a bottleneck for some of your
actors you can consider to implement it at lower level by extending UntypedAbstractActor
instead
of AbstractActor
.
If the validation of the ReceiveBuilder
match logic turns out to be a bottleneck for some of your
actors you can consider to implement it at lower level by extending UntypedAbstractActor
instead
of AbstractActor
. The partial functions created by the ReceiveBuilder
consist of multiple lambda
expressions for every match statement, where each lambda is referencing the code to be run. This is something
that the JVM can have problems optimizing and the resulting code might not be as performant as the
untyped version. When extending UntypedAbstractActor
each message is received as an untyped
Object
and you have to inspect and cast it to the actual message type in other ways (instanceof checks).
This is a one-stop-shop if all you want is an extension which is constructed with the ExtendedActorSystem as its only constructor argument:
This is a one-stop-shop if all you want is an extension which is constructed with the ExtendedActorSystem as its only constructor argument:
object MyExt extends ExtensionKey[Ext] class Ext(system: ExtendedActorSystem) extends Extension { ... }
Java API:
public class MyExt extends Extension { public static final ExtensionKey<MyExt> key = new ExtensionKey<MyExt>(MyExt.class); public MyExt(ExtendedActorSystem system) { ... } }
Note: Don't use this class if the extension is written in Scala and consumed in
Eclipse Java projects. JDT has problems resolving correct type for the
get
method.
(Since version 2.5.0) Use a regular Extension instead
Actor base trait that should be extended by or mixed to create an Actor with the semantics of the 'Actor Model': http://en.wikipedia.org/wiki/Actor_model
Actor base trait that should be extended by or mixed to create an Actor with the semantics of the 'Actor Model': http://en.wikipedia.org/wiki/Actor_model
This class is the Java cousin to the akka.actor.Actor Scala interface. Subclass this abstract class to create a MDB-style untyped actor.
An actor has a well-defined (non-cyclic) life-cycle.
The Actor's own akka.actor.ActorRef is available as getSelf()
, the current
message’s sender as getSender()
and the akka.actor.UntypedActorContext as
getContext()
. The only abstract method is onReceive()
which is invoked for
each processed message unless dynamically overridden using getContext().become()
.
Here is an example on how to create and use an UntypedActor:
public class SampleUntypedActor extends UntypedActor { public static class Reply implements java.io.Serializable { final public ActorRef sender; final public Result result; Reply(ActorRef sender, Result result) { this.sender = sender; this.result = result; } } private static SupervisorStrategy strategy = new OneForOneStrategy(10, Duration.create("1 minute"), new Function<Throwable, Directive>() { @Override public Directive apply(Throwable t) { if (t instanceof ArithmeticException) { return resume(); } else if (t instanceof NullPointerException) { return restart(); } else if (t instanceof IllegalArgumentException) { return stop(); } else { return escalate(); } } }); @Override public SupervisorStrategy supervisorStrategy() { return strategy; } public void onReceive(Object message) throws Exception { if (message instanceof String) { String msg = (String) message; if (msg.equals("UseSender")) { // Reply to original sender of message getSender().tell(msg, getSelf()); } else if (msg.equals("SendToSelf")) { // Send message to the actor itself recursively getSelf().tell("SomeOtherMessage", getSelf()); } else if (msg.equals("ErrorKernelWithDirectReply")) { // Send work to one-off child which will reply directly to original sender getContext().actorOf(Props.create(Worker.class)).tell("DoSomeDangerousWork", getSender()); } else if (msg.equals("ErrorKernelWithReplyHere")) { // Send work to one-off child and collect the answer, reply handled further down getContext().actorOf(Props.create(Worker.class)).tell("DoWorkAndReplyToMe", getSelf()); } else { unhandled(message); } } else if (message instanceof Reply) { final Reply reply = (Reply) message; // might want to do some processing/book-keeping here reply.sender.tell(reply.result, getSelf()); } else { unhandled(message); } } }
(Since version 2.5.0) Use AbstractActor instead of UntypedActor.
UntypedActorContext is the UntypedActor equivalent of ActorContext, containing the Java API
UntypedActorContext is the UntypedActor equivalent of ActorContext, containing the Java API
(Since version 2.5.0) Use AbstractActor.ActorContext instead of UntypedActorContext.
Actor base class that should be extended to create an actor with a stash.
Actor base class that should be extended to create an actor with a stash.
The stash enables an actor to temporarily stash away messages that can not or should not be handled using the actor's current behavior.
Example:
public class MyActorWithStash extends UntypedActorWithStash { int count = 0; public void onReceive(Object msg) { if (msg instanceof String) { if (count < 0) { getSender().tell(new Integer(((String) msg).length()), getSelf()); } else if (count == 2) { count = -1; unstashAll(); } else { count += 1; stash(); } } } }Note that the subclasses of
UntypedActorWithStash
by default request a Deque based mailbox since this class
implements the RequiresMessageQueue<DequeBasedMessageQueueSemantics>
marker interface.
You can override the default mailbox provided when DequeBasedMessageQueueSemantics
are requested via config:
akka.actor.mailbox.requirements { "akka.dispatch.BoundedDequeBasedMessageQueueSemantics" = your-custom-mailbox }Alternatively, you can add your own requirement marker to the actor and configure a mailbox type to be used for your marker.
For a Stash
based actor that enforces unbounded deques see akka.actor.UntypedActorWithUnboundedStash.
There is also an unrestricted version akka.actor.UntypedActorWithUnrestrictedStash that does not
enforce the mailbox type.
(Since version 2.5.0) Use AbstractActorWithStash instead of UntypedActorWithStash.
Actor base class with Stash
that enforces an unbounded deque for the actor.
Actor base class with Stash
that enforces an unbounded deque for the actor.
See akka.actor.UntypedActorWithStash for details on how Stash
works.
(Since version 2.5.0) Use AbstractActorWithUnboundedStash instead of UntypedActorWithUnboundedStash.
Actor base class with Stash
that does not enforce any mailbox type.
Actor base class with Stash
that does not enforce any mailbox type. The proper mailbox has to be configured
manually, and the mailbox should extend the akka.dispatch.DequeBasedMessageQueueSemantics marker trait.
See akka.actor.UntypedActorWithStash for details on how Stash
works.
(Since version 2.5.0) Use AbstractActorWithUnrestrictedStash instead of UntypedActorWithUnrestrictedStash.
Java API: compatible with lambda expressions
Java API: compatible with lambda expressions
Given an ActorPath it returns the Address and the path elements if the path is well-formed
Java API
An ActorSelection is a logical view of a section of an ActorSystem's tree of Actors, allowing for broadcasting of messages to that section.
This object serves as extractor for Scala and as address parser for Java.
A message all Actors will understand, that when processed will make the Actor throw an ActorKilledException, which will trigger supervision.
A message all Actors will understand, that when processed will make the Actor throw an ActorKilledException, which will trigger supervision.
The Local Scope is the default one, which is assumed on all deployments which do not set a different scope.
The Local Scope is the default one, which is assumed on all deployments which do not set a different scope. It is also the only scope handled by the LocalActorRefProvider.
This is an extractor for retrieving the original cause (i.e.
This is an extractor for retrieving the original cause (i.e. the first failure) from a akka.actor.PostRestartException. In the face of multiple “nested” restarts it will walk the origCause-links until it arrives at a non-PostRestartException type.
A message all Actors will understand, that when processed will terminate the Actor permanently.
A message all Actors will understand, that when processed will terminate the Actor permanently.
Factory for Props instances.
Factory for Props instances.
Props is a ActorRef configuration object, that is immutable, so it is thread safe and fully sharable.
Used when creating new actors through ActorSystem.actorOf
and ActorContext.actorOf
.
When using ActorContext.setReceiveTimeout, the singleton instance of ReceiveTimeout will be sent to the Actor when there hasn't been any message for that long.
When using ActorContext.setReceiveTimeout, the singleton instance of ReceiveTimeout will be sent to the Actor when there hasn't been any message for that long.
Extractor for so-called “relative actor paths” as in “relative URI”, not in “relative to some actor”.
Extractor for so-called “relative actor paths” as in “relative URI”, not in “relative to some actor”. Examples:
* "grand/child" * "/user/hello/world"
Classes for passing status back to the sender.
Classes for passing status back to the sender. Used for internal ACKing protocol. But exposed as utility class for user-specific ACKing protocols as well.
This represents the TypedActor Akka Extension, access to the functionality is done through a given ActorSystem.
TypedProps is a TypedActor configuration object, that is thread safe and fully sharable.
TypedProps is a TypedActor configuration object, that is thread safe and fully sharable. It's used in TypedActorFactory.typedActorOf to configure a TypedActor instance.
This object contains elements which make writing actors and related code more concise, e.g.
This object contains elements which make writing actors and related code more concise, e.g. when trying out actors in the REPL.
For the communication of non-actor code with actors, you may use anonymous actors tailored to this job:
import ActorDSL._ import scala.concurrent.util.duration._ implicit val system: ActorSystem = ... implicit val i = inbox() someActor ! someMsg // replies will go to `i` val reply = i.receive() val transformedReply = i.select(5 seconds) { case x: Int => 2 * x }
The receive
and select
methods are synchronous, i.e. they block the
calling thread until an answer from the actor is received or the timeout
expires. The default timeout is taken from configuration item
akka.actor.dsl.default-timeout
.
When defining actors in the REPL, say, you may want to have a look at the
Act
trait:
import ActorDSL._ val system: ActorSystem = ... val a = actor(system, "fred")(new Act { val b = actor("barney")(new Act { ... }) become { case msg => ... } })
Note that actor
can be used with an implicit akka.actor.ActorRefFactory
as shown with "barney"
(where the akka.actor.ActorContext serves this
purpose), but since nested declarations share the same
lexical context "fred"
’s ActorContext would be ambiguous
if the akka.actor.ActorSystem were declared implicit
(this could also
be circumvented by shadowing the name system
within "fred"
).
Note: If you want to use an Act with Stash
, you should use the
ActWithStash
trait in order to have the actor get the necessary deque-based
mailbox setting.
(Since version 2.5.0) deprecated Use the normal actorOf
methods defined on ActorSystem
and ActorContext
to create Actors instead.