Stopping an actor

An actor can be stopped in one of the following ways:

  • By designating its next behavior to be Behaviors.stopped.
  • By applying the stop method of the ActorContext to the immediate child. The child will finish processing the current message but leave other messages that are still in the mailbox unprocessed.
  • By the actor system as it stops its ancestor. The actual shutdown happens recursively, bottom-up, following the hierarchy. 

The most natural approach in our mixers example would be to pick the first option. We implement it in the following example:

object Mixer {
final case class Mix(groceries: Groceries, sender: ActorRef[Collect])
def mix = Behaviors.receiveMessage[Mix] {
case Mix(Groceries(eggs, flour, sugar, chocolate), sender) =>
Thread.sleep(3000)
sender ! Collect(Dough(eggs * 50 + flour + sugar + chocolate))
Behaviors.stopped
}
}

The Mixer behavior is very simple, so we don't need to define an ADT for that and use the single Mix command directly. The Chef actor expects Collect(Dough) back. This obliges us to define it as a type parameter for the sender reference. The behavior itself simulates the hardware delay for the mixing to be finished, sends the prepared dough to the Chef, and returns Behaviors.stopped as the next behavior. This leads to the graceful termination of the Mixer actor.

Now that we've sent the dough back to the Chef, let's see how it is supposed to be handled. The Chef needs to collect the results from all of the mixers it has created. To do so, we could pass references to the child actors we've created in the idle state to the mixing behavior, but let's imagine we lost the references we collected for some reason. In this case, Chef could look up its children.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.97.170