diff --git a/akka-docs/src/main/paradox/typed/actor-lifecycle.md b/akka-docs/src/main/paradox/typed/actor-lifecycle.md index c75511352d..acd643b4d0 100644 --- a/akka-docs/src/main/paradox/typed/actor-lifecycle.md +++ b/akka-docs/src/main/paradox/typed/actor-lifecycle.md @@ -21,6 +21,33 @@ forming an actor hierarchy. @apidoc[akka.actor.typed.ActorSystem] hosts the hier actor at the top of the hierarchy of the `ActorSystem`. The lifecycle of a child actor is tied to the parent -- a child can stop itself or be stopped at any time but it can never outlive its parent. +### The ActorContext + +The ActorContext can be accessed for many purposes such as: + +* Spawning child actors and supervision +* Watching other actors (`DeathWatch`) to receive a `Terminated(otherActor)` event should the watched actor stop permanently +* Logging +* Creating message adapters +* Request-response interactions (ask) with another actor +* Access to the `self` ActorRef + +If a behavior needs to use the `ActorContext`, for example to spawn child actors, or use +@scala[`context.self`]@java[`context.getSelf()`], it can be obtained by wrapping construction with `Behaviors.setup`: + +Scala +: @@snip [BasicPersistentBehaviorCompileOnly.scala](/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BasicPersistentBehaviorCompileOnly.scala) { #actor-context } + +Java +: @@snip [BasicPersistentBehaviorTest.java](/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java) { #actor-context } + +#### ActorContext Thread Safety + +Many of the methods in `ActorContext` are not thread-safe and + +* Must not be accessed by threads from @scala[`scala.concurrent.Future`]@java[`java.util.concurrent.CompletionStage`] callbacks +* Must not be shared between several actor instances +* Should only be used in the ordinary actor message processing thread ### The Guardian Actor diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java index ce53408ce8..93c8108d98 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java @@ -4,6 +4,7 @@ package jdocs.akka.persistence.typed; +import akka.actor.typed.ActorRef; import akka.actor.typed.Behavior; import akka.actor.typed.SupervisorStrategy; import akka.actor.typed.javadsl.ActorContext; @@ -341,9 +342,13 @@ public class BasicPersistentBehaviorTest { // this makes the context available to the command handler etc. private final ActorContext ctx; + // optionally if you only need `ActorContext.getSelf()` + private final ActorRef self; + public MyPersistentBehavior(PersistenceId persistenceId, ActorContext ctx) { super(persistenceId); this.ctx = ctx; + this.self = ctx.getSelf(); } // #actor-context