13.6. Stopping Actors

Problem

You want to stop one or more running Akka actors.

Solution

There are several ways to stop Akka actors. The most common ways are to call system.stop(actorRef) at the ActorSystem level or context.stop(actorRef) from inside an actor.

There are other ways to stop an actor:

  • Send the actor a PoisonPill message.

  • Program a gracefulStop.

To demonstrate these alternatives, at the ActorSystem level you can stop an actor by using the ActorSystem instance:

actorSystem.stop(anActor)

Within an actor, you can stop a child actor by using the context reference:

context.stop(childActor)

An actor can also stop itself:

context.stop(self)

You can stop an actor by sending it a PoisonPill message:

actor ! PoisonPill

The gracefulStop is a little more complicated and involves the use of a future. See the Discussion for a complete example.

Discussion

Table 13-2 provides a summary of the methods that you can use to stop an actor.

Table 13-2. Ways to stop actors

Message

Description

stop method

The actor will continue to process its current message (if any), but no additional messages will be processed. See additional notes in the paragraphs that follow.

PoisonPill message

A PoisonPill message will stop an actor when the message is processed. A PoisonPill message is queued just like an ordinary message and will be handled after other messages queued ahead of it in its mailbox.

gracefulStop method

Lets you attempt to terminate actors gracefully, waiting for them to timeout. The documentation states that this ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.