The main reason for the usage of Props in Akka is that the lifecycle of the Actor
instances are completely managed by the ActorSystem
.
In the simplest case, your Actor
will be instantiated once, and then chug along happily. If that was the only use case, then a standard dependency injection approach would probably work.
However, that simplest case is thrown out the window once the Akka supervision mechanisms kicks in. In Akka, when an Actor
throws an Exception
, a supervision mechanism decides what should happen to that actor. Typically, the supervisor has to decided if:
- The exception is expected and doesn't really cause a problem => The actor is resumed and continues operating as normal.
- The exception is fatal, and the actor cannot be allowed to continue => The actor is killed, its mailbox is destroyed and all of the messages it contains are sent to the dead letters.
- The exception is bad but recoverable => The actor is restarted. This means that the existing
Actor
instance is discarded but its mailbox is retained. A new, fresh Actor
instance is created from the Props
, and will start processing the original mailbox.
The Props
mechanism is required for handling the restarting case.
I believe that the Props mechanism is also useful when creating a distributed ActorSystem
, as it allows instantiating the Actor
on another JVM if necessary.
All those cases cannot be handled by a standard factory pattern or by standard dependency injection mechanisms.