Akka tutorial has the following code: http://doc.akka.io/docs/akka/2.0.2/intro/getting-started-first-java.html
public void calculate (final int nrOfWorkers, final int nrOfElements, final int nrOfMessages){
ActorSystem system = ActorSystem.create("PiSystem");
final ActorRef listener = system.actorOf(Props.create(Listener.class), "listener");
ActorRef master = system.actorOf(new Props(new UntypedActorFactory() {
public UntypedActor create() {
return new Master(nrOfWorkers, nrOfMessages, nrOfElements, listener);
}
}), "master");
master.tell(new Calculate(), ActorRef.noSender());
}
in which, UntypedActorFactory
is deprecated.
So I tried to use Props.create
such as
ActorRef master = system.actorOf( Props.create(
new Creator<Master>(){
public Master create(){
return new Master(nrOfWorkers, nrOfMessages, nrOfElements, listener);
}
}), "master");
And there is Exception saying
cannot use non-static local Creator to create actors; make it static or top-level
so I start to write a static class, which has parameters needed to be passed.
static class LocalCreator implements Creator<Master>{
public Master create(){
return new Master(nrOfWorkers, nrOfMessages, nrOfElements, listener);
}
}
How to pass the parameters nrOfWorkers and etc. into the create()
function elegantly?
If you read the Akka docs (Java flavor), it lists two ways you can construct an actor that has constructor params. The first is like so (using your example classes):
ActorSystem system = ActorSystem.create("PiSystem");
final ActorRef listener = system.actorOf(Props.create(Listener.class), "listener");
ActorRef master = system.actorOf(Props.create(Master.class, nrOfWorkers, nrOfMessages, nrOfElements, listener), "master");
master.tell(new Calculate(), ActorRef.noSender());
Or if you don't want to go that route, you can use a Creator
like so:
public class MasterCreator implements Creator<Master>{
private int nrOfWorkers, nrOfMessages, nrOfElements;
private ActorRef listener;
public MasterCreator(int nrOfWorkers, int nrOfMessages, int nrOfElements, ActorRef listener){
this.listener = listener;
this.nrOfElements = nrOfElements;
this.nrOfMessages = nrOfMessages;
this.nrOfWorkers = nrOfWorkers;
}
public Master create(){
return new Master(nrOfWorkers, nrOfMessages, nrOfElements, listener);
}
}
And then use it like this:
ActorSystem system = ActorSystem.create("PiSystem");
final ActorRef listener = system.actorOf(Props.create(Listener.class), "listener");
ActorRef master = system.actorOf(Props.create(new MasterCreator(nrOfWorkers, nrOfMessages, nrOfElements, listener)), "master");
master.tell(new Calculate(), ActorRef.noSender());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With