简体   繁体   中英

Understanding Props for actor creation

I'm trying to undersatnd how to use Props correctly. My first thought was that Props objects contain some property of the actor being created. These properties might include the actor's field values as well as some deployment related information (eeg which dispatcher to use). The later has nothing to do with the actual actor and therefore should be shipped independent.

But in the documentation said the the good practice is to use static factory method within the actor like this (documentation removed):

public class DemoActor extends UntypedActor {

  public static Props props(final int magicNumber) {
    return Props.create(new Creator<DemoActor>() {
      private static final long serialVersionUID = 1L;

      @Override
      public DemoActor create() throws Exception {
        return new DemoActor(magicNumber);
      }
    });
  }
}

I think this is not quite good if for instance we want to use one dispatcher now, and the requirements will change at some point in the future. It will lead to modifying the Actor class which is (in my opinion) incorrect.

The static factory method, I believe, may be particularly useful for Java, which tends to get quite verbose with Akka. While the code you've shown is for the Actor class, you will also usually have some Inversion-of-Control style configuration or bootstrapper class where you typically set up the actor system and then the actors with the ActorSystem#actorOf class.

Now, after retrieving the base Props instance from the Actor's props factory method you can configure it a bit to your purposes ( Props is immutable but have methods returning modified instances). In case you need a different dispatcher then you will just modify your bootstrapper class from something like this:

ActorSystem system = ...;
system.actorOf(DemoActor.props(42), "demo-with-default-dispatcher");

to:

system.actorOf(DemoActor.props(42).withDispatcher("DemoDispatcher"), "demo-with-configured-dispatcher");

(these are just minimal code snippets but I think you get the idea)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM