Skip to content

Actors

An actor is an object that owns some state and handles messages one at a time. Code outside the actor never touches that state: it sends a message, and the actor changes its state while it handles the message. Because only one message runs at a time, the actor needs no locks.

Use an actor when something has state that many requests change at once (a counter, a chat room, an order, a session, an AI agent's conversation), when work should run in the background without blocking the caller, or when you want a failure to restart one small part of the system instead of the request.

This page covers defining actors, Spring dependency injection, actor ids, spawning and finding actors, stopping them, and child actors. Sending messages is in Messaging, failures in Supervision, and the tools inside an actor (state, timers, watching) in Behaviors.

Setup

Add actor-spring-boot-starter to your Spring Boot application, as shown in Getting Started. That starts one actor system for the Spring context and gives you a SpringActorSystem bean to inject. Nothing else is needed for the features on this page.

Defining an actor

An actor is a Spring bean that implements SpringActor<C>, where C is the type of the messages it accepts (its commands). It has one method, create, which returns the actor's behavior: which handler runs for which message.

import io.github.seonwkim.actor.AskCommand;
import io.github.seonwkim.actor.SpringActor;
import io.github.seonwkim.actor.SpringActorBehavior;
import io.github.seonwkim.actor.SpringActorContext;
import org.springframework.stereotype.Component;

@Component
public class GreeterActor implements SpringActor<GreeterActor.Command> {

    // Every message this actor accepts implements Command.
    public interface Command {}

    // A message that expects no answer.
    public record LogVisit(String name) implements Command {}

    // A message that expects a String answer: it extends AskCommand<String>.
    public static class Greet extends AskCommand<String> implements Command {
        public final String name;

        public Greet(String name) {
            this.name = name;
        }
    }

    @Override
    public SpringActorBehavior<Command> create(SpringActorContext actorContext) {
        return SpringActorBehavior.builder(Command.class, actorContext)
                .onMessage(LogVisit.class, (ctx, msg) -> {
                    ctx.getLog().info("{} visited", msg.name());
                    return SpringActorBehavior.same();
                })
                .onMessage(Greet.class, (ctx, msg) -> {
                    msg.reply("Hello, " + msg.name + "!");
                    return SpringActorBehavior.same();
                })
                .build();
    }
}
import io.github.seonwkim.actor.AskCommand
import io.github.seonwkim.actor.SpringActor
import io.github.seonwkim.actor.SpringActorBehavior
import io.github.seonwkim.actor.SpringActorContext
import io.github.seonwkim.actor.kotlin.behavior
import org.springframework.stereotype.Component

@Component
class GreeterActor : SpringActor<GreeterActor.Command> {

    // Every message this actor accepts implements Command.
    sealed interface Command

    // A message that expects no answer.
    data class LogVisit(val name: String) : Command

    // A message that expects a String answer: it extends AskCommand<String>.
    class Greet(val name: String) : AskCommand<String>(), Command

    override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
        behavior<Command>(actorContext) {
            onMessage<LogVisit> { msg ->
                log.info("{} visited", msg.name)
                same()
            }
            onMessage<Greet> { msg ->
                msg.reply("Hello, ${msg.name}!")
                same()
            }
        }
}

What each part does:

  • @Component makes the class a Spring bean. The starter finds every bean that implements SpringActor (or SpringActorWithContext) and registers it as an actor type. A @Bean method works too.
  • Command is the actor's message type. Each message is a class that implements it. Make messages immutable: records or classes with final fields (data class / val in Kotlin).
  • AskCommand<R> marks a message that expects an answer of type R. The handler answers with msg.reply(value). See Messaging.
  • create runs once each time an actor of this class is spawned. It gets the actor's context (actorContext.actorId() is the id it was spawned with) and returns the behavior.
  • onMessage(Type, handler) registers a handler. The handler gets the behavior context (ctx: logger, self reference, timers, children) and the message, and returns the next behavior. same() means "keep handling messages this way". See Behaviors for the other return values and for keeping state in the actor.

In Kotlin, behavior<Command>(actorContext) { ... } comes from the actor-kotlin module and builds the same behavior with SpringActorBehavior.builder: onMessage<Greet> { msg -> ... } is .onMessage(Greet.class, (ctx, msg) -> ...), and the handler runs with the behavior context as this, so log is ctx.getLog(). See the Kotlin guide.

Spring dependency injection

Actors are ordinary Spring beans, so they get their dependencies through the constructor (or any other injection style):

@Component
public class OrderActor implements SpringActor<OrderActor.Command> {

    private final OrderRepository orderRepository;

    public OrderActor(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    public interface Command {}

    public record MarkPaid(long orderId) implements Command {}

    @Override
    public SpringActorBehavior<Command> create(SpringActorContext actorContext) {
        return SpringActorBehavior.builder(Command.class, actorContext)
                .onMessage(MarkPaid.class, (ctx, msg) -> {
                    orderRepository.markPaid(msg.orderId());
                    return SpringActorBehavior.same();
                })
                .build();
    }
}
@Component
class OrderActor(private val orderRepository: OrderRepository) : SpringActor<OrderActor.Command> {

    sealed interface Command

    data class MarkPaid(val orderId: Long) : Command

    override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
        behavior<Command>(actorContext) {
            onMessage<MarkPaid> { msg ->
                orderRepository.markPaid(msg.orderId)
                same()
            }
        }
}

Spring creates one OrderActor bean, and every actor spawned from that class calls create on that same bean. Keep injected services in final fields, and per-actor state in the behavior, as the next section shows.

What not to do in an actor bean

Don't

  • Don't keep state in bean fields. A field of the bean is shared by every actor of the class and changed from many threads at once, which breaks the "one message at a time, no locks" guarantee. Keep per-actor state in the behavior: the state object of withState.
  • Don't block the default dispatcher. A JPA repository or a blocking HTTP client holds the thread while it waits, and the default dispatcher's few threads run out. Spawn such actors with withBlockingDispatcher() (see Dispatchers), or call a non-blocking client and turn its CompletionStage into a message with pipeToSelf.
  • Don't put proxy annotations on an actor bean. @Transactional, @Async or @Cacheable make Spring wrap the bean in a proxy, but the handlers run in the behavior that create returns, not through the proxy, so the advice never applies to them, and a transaction can't span messages anyway. Put @Transactional on a separate service the handler calls.
@Service
public class PaymentService {

    @Transactional   // on the service, not on the actor
    public void markPaid(long orderId) {
        // update the order and the ledger in one transaction
    }
}

@Component
public class OrderActor implements SpringActor<OrderActor.Command> {

    private final PaymentService payments;   // wiring: injected and final
    // private int paidCount;                // don't: shared by every OrderActor

    public OrderActor(PaymentService payments) {
        this.payments = payments;
    }

    public interface Command {}

    public record MarkPaid(long orderId) implements Command {}

    @Override
    public SpringActorBehavior<Command> create(SpringActorContext actorContext) {
        return SpringActorBehavior.builder(Command.class, actorContext)
                .withState(ctx -> new Paid())   // one per actor
                .onMessage(MarkPaid.class, (paid, msg) -> {
                    payments.markPaid(msg.orderId());   // blocks: see the spawn below
                    paid.count++;
                    return SpringActorBehavior.same();
                })
                .build();
    }

    private static class Paid {
        int count;   // only this actor's thread touches it
    }
}

// The handler waits on the database, so the actor runs on the blocking dispatcher.
actorSystem.actor(OrderActor.class).withId("order-42").withBlockingDispatcher().getOrSpawn();
@Service
class PaymentService {

    @Transactional   // on the service, not on the actor
    fun markPaid(orderId: Long) {
        // update the order and the ledger in one transaction
    }
}

@Component
class OrderActor(private val payments: PaymentService) : SpringActor<OrderActor.Command> {
    // private var paidCount = 0   // don't: shared by every OrderActor

    sealed interface Command

    data class MarkPaid(val orderId: Long) : Command

    override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
        behavior<Command, Paid>(actorContext, state = { Paid() }) {   // one per actor
            onMessage<MarkPaid> { msg ->
                payments.markPaid(msg.orderId)   // blocks: see the spawn below
                count++
                same()
            }
        }

    private class Paid {
        var count = 0   // only this actor's thread touches it
    }
}

// The handler waits on the database, so the actor runs on the blocking dispatcher.
actorSystem.actor<OrderActor, OrderActor.Command>().withId("order-42").withBlockingDispatcher().getOrSpawn()

The starter checks the first and the last rule when it starts. For each actor bean (SpringActor, SpringShardedActor) it logs a warning for every instance field that is neither static nor final, superclasses included, and for a bean that is a Spring AOP proxy. Fields Spring injects are wiring, not state, and don't count: those annotated with @Autowired, @Value, @Inject or @Resource, those set through a setter with one of these annotations, and properties set on the bean definition. A final field that holds a mutable object (a HashMap, an AtomicInteger) is shared just the same, but the check can't tell it apart from a service, so it doesn't report it.

spring.actor.validation.actor-beans Effect
warn (default) Logs one warning per problem, naming the bean, its class and the field
fail Stops startup with an error that lists the problems
off Doesn't check

Actor ids

Every actor has an id: the string you pass to withId(...) or getOrSpawn(..., id). The starter names the actor <fully.qualified.ClassName>:<id>, so:

  • An id is unique per actor class. OrderActor "42" and InvoiceActor "42" are two different actors.
  • An id is unique within its parent. Top-level actors (spawned from SpringActorSystem) share one parent on each node; a child's id only has to be unique among its parent's children.
  • A plain actor lives on the node that spawned it. In cluster mode, get and exists on another node don't see it. For one actor per id across the whole cluster, use sharded actors; for one actor per cluster, use cluster singletons.

Use ids that come from your domain, such as an order id or a user id, so any request can find its actor again.

Spawning and finding actors

Inject SpringActorSystem wherever you need an actor. Every call returns a CompletionStage (the Kotlin module adds suspend versions).

Method What it does Default timeout When it does not work out
getOrSpawn(Class, id) Returns the running actor, or spawns it with default settings 3 s Fails if the spawn fails
find(Class, id) Returns the running actor 3 s Completes with an empty Optional when there is none; fails on timeout
exists(Class, id) Says whether the actor runs 3 s Completes with false when there is none; fails on timeout
actor(Class) Starts a spawn builder for custom settings (see below) 3 s

Each method has an overload with a Duration timeout as the last argument.

getOrSpawn: the usual way

getOrSpawn is the simplest way to use an actor. Call it on every request with the id from the request; the first call spawns the actor, later calls return it.

@Service
public class GreeterService {
    private final SpringActorSystem actorSystem;

    public GreeterService(SpringActorSystem actorSystem) {
        this.actorSystem = actorSystem;
    }

    public CompletionStage<String> greet(String name) {
        return actorSystem.getOrSpawn(GreeterActor.class, "greeter")
                .thenCompose(greeter -> greeter
                        .ask(new GreeterActor.Greet(name))
                        .withTimeout(Duration.ofSeconds(3))
                        .execute());
    }
}
@Service
class GreeterService(private val actorSystem: SpringActorSystem) {

    // A suspend function: call it from a coroutine or a suspend controller method.
    suspend fun greet(name: String): String =
        actorSystem.awaitGetOrSpawn<GreeterActor, _>("greeter")
            .awaitAsk(GreeterActor.Greet(name), timeout = 3.seconds)
}

In a WebFlux application, wrap the stage with Mono.fromCompletionStage(...) (Java) or use a suspend controller method (Kotlin).

getOrSpawn checks for the running actor and spawns it in one step, so callers that ask for the same new id at the same moment all get the same actor.

The spawn builder: custom settings

actorSystem.actor(Class) returns a builder. Set the id and any options, then end with spawn(), getOrSpawn() or spawnAndWait():

CompletionStage<SpringActorHandle<OrderActor.Command>> order = actorSystem
        .actor(OrderActor.class)
        .withId("order-42")
        .withBlockingDispatcher()                       // it calls a JPA repository
        .withMailbox(MailboxConfig.bounded(1_000))
        .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(3, Duration.ofMinutes(1)))
        .withTimeout(Duration.ofSeconds(5))
        .getOrSpawn();
// In a suspend function
val order: SpringActorHandle<OrderActor.Command> = actorSystem
    .actor<OrderActor, _>()
    .withId("order-42")
    .withBlockingDispatcher()                       // it calls a JPA repository
    .withMailbox(MailboxConfig.bounded(1_000))
    .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(3, 1.minutes))
    .withTimeout(5.seconds)
    .awaitGetOrSpawn()
Builder method What it sets Default
withId(String) The actor id. Required unless you pass a context. none
withContext(SpringActorContext) A custom context (see Custom actor context). Its actorId() is the id. a context holding the id
withTimeout(Duration) How long to wait for the spawn 3 s
withSupervisionStrategy(...) What happens when a handler throws. See Supervision. stop
withDefaultDispatcher(), withBlockingDispatcher(), withDispatcherFromConfig(name), withDispatcherSameAsParent() The thread pool. See Dispatchers. default dispatcher
withMailbox(MailboxConfig) The mailbox: MailboxConfig.bounded(n) or MailboxConfig.fromConfig(name). See Mailboxes. unbounded
withTags(TagsConfig) Tags in the pekkoTags log field. See Logging. none
withMdc(MdcConfig) Fixed MDC values on every log line of the actor. See Logging. none
asClusterSingleton() One instance in the cluster. Cluster mode only. See Singletons. off
Ending Returns Notes
spawn() CompletionStage<SpringActorHandle<C>> Fails if an actor with this class and id already runs
getOrSpawn() CompletionStage<SpringActorHandle<C>> Returns the running actor if there is one; the options apply only when it spawns
spawnAndWait() SpringActorHandle<C> Blocks the calling thread until the actor runs

actorSystem.getOrSpawn(Class, id) is actor(Class).withId(id).getOrSpawn() with every option at its default.

Don't block where threads are shared

spawnAndWait() (and .toCompletableFuture().join() on any stage) blocks the calling thread. That is fine in a test or at startup, but not inside an actor's handler or a WebFlux pipeline: compose the stage instead, or use the suspend functions in Kotlin.

find and exists

find returns a handle to a running actor and exists says whether one runs. Neither spawns anything. Use them when an absent actor means something to your code, for example "this order was never opened":

actorSystem.find(OrderActor.class, "order-42").thenAccept(order -> order.ifPresentOrElse(
        o -> o.tell(new OrderActor.MarkPaid(42)),
        () -> log.info("order-42 is not running")));
// In a suspend function
val order = actorSystem.awaitGet<OrderActor, _>("order-42")
if (order == null) {
    log.info("order-42 is not running")
} else {
    order.tell(OrderActor.MarkPaid(42))
}

Both look at the top-level actors of this node and at the cluster singletons this node spawned. When the actor system doesn't answer within the timeout (3 s by default), the stage fails with a TimeoutException; it never reports a running actor as missing.

get(Class, id), which completes with null when no actor runs, is deprecated: use find.

Spawning a top-level actor, find and exists are each a request to one actor on the node, which keeps the top-level actors as its children and answers in turn. That suits up to hundreds of long-lived actors, looked up once and kept (see below). For an actor per user, order or session that is created and stopped often, use sharded actors: you send to an id, the shard region routes the message without asking that one actor, and the entity starts on its first message and stops when idle. They also run on one node, as a one-node cluster (spring.actor.cluster.join-self).

Keeping a handle

A SpringActorHandle stays valid for as long as the actor runs, and sending through it costs nothing extra. If a service talks to the same actor on every request, look it up once and keep the stage:

@Service
public class CounterService {
    private final SpringActorSystem actorSystem;
    private final AtomicReference<CompletionStage<SpringActorHandle<CounterActor.Command>>> counter =
            new AtomicReference<>();

    public CounterService(SpringActorSystem actorSystem) {
        this.actorSystem = actorSystem;
    }

    private CompletionStage<SpringActorHandle<CounterActor.Command>> counter() {
        return counter.updateAndGet(existing ->
                existing != null ? existing : actorSystem.getOrSpawn(CounterActor.class, "counter"));
    }

    public CompletionStage<Long> increment() {
        return counter().thenCompose(c -> c.ask(new CounterActor.Increment()).execute());
    }
}
@Service
class CounterService(private val actorSystem: SpringActorSystem) {

    // Spawned on first use; later calls reuse the same handle.
    private val counter = AtomicReference<CompletionStage<SpringActorHandle<CounterActor.Command>>>()

    private fun counter(): CompletionStage<SpringActorHandle<CounterActor.Command>> =
        counter.updateAndGet { existing ->
            existing ?: actorSystem.getOrSpawn(CounterActor::class.java, "counter")
        }

    suspend fun increment(): Long = counter().await().awaitAsk(CounterActor.Increment())
}

A kept handle points at one actor. If that actor stops, messages sent through the handle are lost (they go to dead letters). Keep handles only to actors that live as long as the service, or look the actor up again after it stops.

Spawning at startup

A bean may spawn its actors in its constructor or in a @PostConstruct method, as the logging example's OrderService does. Spring may not have created the actor's bean yet at that point (beans are created in an order you don't control); the spawn then asks Spring for the actor bean first, so it gets created on the spot. Blocking with spawnAndWait() is fine there, since startup runs on Spring's own thread.

@Service
public class OrderService {
    private final SpringActorHandle<OrderActor.Command> orders;

    public OrderService(SpringActorSystem actorSystem) {
        this.orders = actorSystem.actor(OrderActor.class).withId("orders").spawnAndWait();
    }
}
@Service
class OrderService(actorSystem: SpringActorSystem) {
    private val orders: SpringActorHandle<OrderActor.Command> =
        actorSystem.actor(OrderActor::class.java).withId("orders").spawnAndWait()
}

The actor class must be a bean of the same application context (for example annotated with @Component). If it isn't, the spawn fails with "No factory registered for class ...".

Custom actor context

SpringActor<C> receives a plain SpringActorContext, which holds the actor id. To give an actor more than its id when it starts, define your own context class and implement SpringActorWithContext<C, CTX> instead:

@Component
public class ReportActor implements SpringActorWithContext<ReportActor.Command, ReportActor.ReportContext> {

    public static class ReportContext extends SpringActorContext {
        private final String reportId;
        final String ownerEmail;

        public ReportContext(String reportId, String ownerEmail) {
            this.reportId = reportId;
            this.ownerEmail = ownerEmail;
        }

        @Override
        public String actorId() {
            return reportId;
        }
    }

    public interface Command {}

    public record Build() implements Command {}

    @Override
    public SpringActorBehavior<Command> create(ReportContext actorContext) {
        return SpringActorBehavior.builder(Command.class, actorContext)
                .onMessage(Build.class, (ctx, msg) -> {
                    ctx.getLog().info("Building {} for {}", actorContext.actorId(), actorContext.ownerEmail);
                    return SpringActorBehavior.same();
                })
                .build();
    }
}

// Spawning it
actorSystem.actor(ReportActor.class)
        .withContext(new ReportActor.ReportContext("report-7", "kim@example.com"))
        .getOrSpawn();
@Component
class ReportActor : SpringActorWithContext<ReportActor.Command, ReportActor.ReportContext> {

    class ReportContext(private val reportId: String, val ownerEmail: String) : SpringActorContext() {
        override fun actorId(): String = reportId
    }

    sealed interface Command

    class Build : Command

    override fun create(actorContext: ReportContext): SpringActorBehavior<Command> =
        behavior<Command>(actorContext) {
            onMessage<Build> {
                log.info("Building {} for {}", actorContext.actorId(), actorContext.ownerEmail)
                same()
            }
        }
}

// Spawning it, in a suspend function
actorSystem.actor<ReportActor, _>()
    .withContext(ReportActor.ReportContext("report-7", "kim@example.com"))
    .awaitGetOrSpawn()

Always spawn such an actor through the builder with withContext(...). A spawn by id alone (actorSystem.getOrSpawn(ReportActor.class, id), or withId(...) without withContext) can't build a ReportContext, so its stage fails with an IllegalArgumentException that names the context type and says to use withContext(...). find and exists work as usual: they only need the id.

Stopping actors

An actor runs until it is stopped. There are three ways to stop one:

From How Notes
Outside the actor handle.stop() The stop request goes into the mailbox, so messages sent before it are handled first.
Inside the actor return SpringActorBehavior.stopped() from a handler Stops after the current message.
A parent ctx.stop(childRef) in the parent's handler Only for the parent's own children.

When an actor stops, its PostStop signal handler runs (see Behaviors), its children stop, and messages still in its mailbox are dropped. Stopping is final: to use the id again, spawn a new actor. Stopping takes a moment, so a spawn with the same id right after stop() can still find the name taken; getOrSpawn after the old actor is gone, or watch it and spawn on ActorTerminated.

An idle actor is not stopped for you. If you create one actor per user or per order, stop it when its work is done (for example with a timer that fires after some idle time), or use sharded actors, which can passivate idle entities.

Child actors

An actor can spawn its own actors, called children. Use children to split work under one owner: a ParentSupervisor with a worker per task, a chat room with an actor per connection. Children are tied to their parent:

  • A child stops when its parent stops.
  • The parent decides how each child is supervised (see Supervision).
  • A child's id only has to be unique among its parent's children.

Enable child operations on the parent

Spawning, finding and checking children works through messages that the parent handles for you. They are turned on when the parent's command type extends FrameworkCommand:

public interface Command extends FrameworkCommand {}
sealed interface Command : FrameworkCommand

Without it, the parent ignores these requests, and every child operation fails with a timeout.

Spawning children from inside the parent

Inside a handler, ctx.getSelf() is a handle to the parent. Call child(ChildClass) on it to get a child builder. The spawn is a message to the parent itself, and the parent handles it after the current message. So never wait for it inside the handler (spawnAndWait() or join()): the parent would wait for a message it can't handle until it finishes waiting, and the spawn times out. Use pipeToSelf to get the result back as a message instead:

@Component
public class DispatcherActor implements SpringActor<DispatcherActor.Command> {

    public interface Command extends FrameworkCommand {}

    public record Assign(String workerId, String task) implements Command {}

    // The result of a child spawn, delivered back to this actor as a message.
    record WorkerReady(Assign assign, SpringActorHandle<WorkerActor.Command> worker, Throwable error)
            implements Command {}

    @Override
    public SpringActorBehavior<Command> create(SpringActorContext actorContext) {
        return SpringActorBehavior.builder(Command.class, actorContext)
                .onMessage(Assign.class, (ctx, msg) -> {
                    ctx.pipeToSelf(
                            ctx.getSelf()
                                    .child(WorkerActor.class)
                                    .withId(msg.workerId())
                                    .withSupervisionStrategy(SupervisionStrategy.restart())
                                    .getOrSpawn(),
                            (worker, error) -> new WorkerReady(msg, worker, error));
                    return SpringActorBehavior.same();
                })
                .onMessage(WorkerReady.class, (ctx, msg) -> {
                    if (msg.error() != null) {
                        ctx.getLog().error("Could not start worker {}", msg.assign().workerId(), msg.error());
                    } else {
                        msg.worker().tell(new WorkerActor.DoTask(msg.assign().task()));
                    }
                    return SpringActorBehavior.same();
                })
                .build();
    }
}
@Component
class DispatcherActor : SpringActor<DispatcherActor.Command> {

    sealed interface Command : FrameworkCommand

    data class Assign(val workerId: String, val task: String) : Command

    // The result of a child spawn, delivered back to this actor as a message.
    data class WorkerReady(
        val assign: Assign,
        val worker: SpringActorHandle<WorkerActor.Command>?,
        val error: Throwable?,
    ) : Command

    override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
        behavior<Command>(actorContext) {
            onMessage<Assign> { msg ->
                pipeToSelf(
                    self.child<WorkerActor, _>()
                        .withId(msg.workerId)
                        .withSupervisionStrategy(SupervisionStrategy.restart())
                        .getOrSpawn(),
                ) { worker, error -> WorkerReady(msg, worker, error) }
                same()
            }
            onMessage<WorkerReady> { msg ->
                val worker = msg.worker
                if (msg.error != null || worker == null) {
                    log.error("Could not start worker {}", msg.assign.workerId, msg.error)
                } else {
                    worker.tell(WorkerActor.DoTask(msg.assign.task))
                }
                same()
            }
        }
}

WorkerActor is an ordinary actor (@Component, SpringActor<WorkerActor.Command>). Children get Spring dependency injection like any other actor.

You can also start children when the parent starts, in the withState factory: call spawn() there and don't wait for the result.

Child operations

The child builder (handle.child(ChildClass)) has the same shape as the spawn builder:

Method Notes
withId(id) or withContext(ctx) Required
withSupervisionStrategy(strategy) How the parent handles the child's failures. Default: stop.
withTimeout(duration) Default 3 s
withDispatcher(DispatcherConfig) DispatcherConfig.blocking(), .sameAsParent(), .fromConfig(name), .defaultDispatcher()
withMailbox(MailboxConfig), withTags(TagsConfig), withMdc(MdcConfig) As for top-level actors
spawn() Spawns the child. If a child with that class and id already runs, returns it and logs a deprecation warning: use getOrSpawn() for that. In 2.0 it fails, like a top-level spawn().
getOrSpawn() Returns the running child, or spawns it (in one step, so concurrent calls get the same child)
spawnAndWait() Blocks until the child runs. Never call it inside the parent.
get() Deprecated: use handle.child(ChildClass, id).get(), which returns an Optional
exists() Whether the child runs

For lookups only, handle.child(ChildClass, id) returns a child reference whose get() completes with an Optional:

CompletionStage<Optional<SpringActorHandle<WorkerActor.Command>>> worker =
        dispatcher.child(WorkerActor.class, "worker-1").get();
CompletionStage<Boolean> running =
        dispatcher.child(WorkerActor.class, "worker-1").withTimeout(Duration.ofSeconds(1)).exists();
// In a suspend function
val worker: SpringActorHandle<WorkerActor.Command>? =
    dispatcher.child<WorkerActor, _>("worker-1").awaitGet()   // null when it doesn't run
val running: Boolean =
    dispatcher.child<WorkerActor, _>("worker-1").withTimeout(1.seconds).awaitExists()

These calls work from outside the parent too: any code with the parent's handle (here dispatcher) can spawn, find or check its children.

Differences from top-level actors:

  • One rule for a taken id: spawn() is for a new actor and getOrSpawn() reuses a running one. A top-level spawn() fails when the id is taken. A child spawn() still returns the running child, with a deprecation warning, until 2.0.
  • A child can't be a cluster singleton.
  • Dispatchers are set with withDispatcher(DispatcherConfig...) instead of the with...Dispatcher() shortcuts.

Inside the parent's handlers, ctx.getChildren() lists the running children and ctx.stop(child) stops one (see Behaviors).

Pitfalls

  • State in bean fields. All actors of a class share the bean. Keep per-actor state in withState. See What not to do in an actor bean.
  • Blocking inside an actor. Waiting on a future, spawnAndWait(), Thread.sleep or blocking I/O on the default dispatcher holds a shared thread. Use pipeToSelf, or the blocking dispatcher for blocking I/O.
  • Child operations time out. The parent's command type doesn't extend FrameworkCommand, or the parent is waiting inside a handler.
  • Second spawn() with the same id fails. Use getOrSpawn(), or check exists first.
  • Actors that are never stopped. One actor per request or per user, never stopped, grows memory without bound.
  • Messaging: tell, ask, replies and message adapters
  • Supervision: what happens when a handler throws
  • Behaviors: state, timers, watching, lifecycle signals
  • Dispatchers: thread pools and mailboxes
  • Sharded actors: one actor per id across a cluster
  • Kotlin: the actor-kotlin helpers used in the Kotlin tabs