Question: Reset Akka actors to initial state

Question

Reset Akka actors to initial state

Answers 1
Added at 2017-01-01 20:01
Tags
Question

I have actors that do a simulation, and then send back data. I would like to be able to run the simulation multiple times, so I need to reset the internal states of each actor.

How can I reset the internal state of an actor, so that that it has the same state as when I created it?

Answers to

Reset Akka actors to initial state

nr: #1 dodano: 2017-01-02 03:01

There are two ways to do it

Manual resetting

Handle a message called as reset and re-initialize all the actor state by yourself manually.

Here is the code sample which handles reset string message and resets the state of the actor.

class FooActor extends Actor {
  var maybeBars: Option[ActorRef] = _
  def receive = {
    case "foo" => println("foo")
    case "reset" => maybeBars = _
  }
}

Automatic resetting

Second way is to throw an exception in the actor and kill the actor. In this case akka default supervisor strategy will restart the actor with initial empty state.

class FooActor extends Actor {
  var maybeBars: Option[ActorRef] = _
  def receive = {
    case "foo" => println("foo")
    case "reset" => throw new Exception("reset")
  }
}
Source Show
◀ Wstecz