I've writen a test class as following:
public class Test {
interface Api {
public int doWork(String worker);
}
interface Worker {
public int work();
}
public static class Worker1Impl extends akka.actor.TypedActor
implements Worker {
@Override
public int work() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("work1 : " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
}
}
public static class Worker2Impl extends akka.actor.TypedActor
implements Worker {
@Override
public int work() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("work2 : " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return 2;
}
}
public static class ApiImpl extends akka.actor.TypedActor
implements Api {
Worker work1 = (Worker) TypedActor.newInstance(Worker.class,
Worker1Impl.class, 20000);
Worker work2 = (Worker) TypedActor.newInstance(Worker.class,
Worker2Impl.class, 20000);
@Override
public int doWork(String worker) {
if(worker.equals("worker1")){
return
work1.work();
}else{
return
work2.work();
}
}
}
public static void main(String[] args) {
Api api = (Api) TypedActor.newInstance(Api.class,
ApiImpl.class, 20000);
api.doWork("worker1");
api.doWork("worker2");
}
}
The result is:
work1 : 0
work1 : 1
work1 : 2
work1 : 3
work1 : 4
work2 : 0
work2 : 1
work2 : 2
work2 : 3
work2 : 4
This is reasonable because actors do theirs jobs in mailbox one by
one. So until worker1 returns the api actor won't send the request to
worker2.
But which I need is that the api actor works like a dispatcher/
replicator so it can forward the request to workers and handle next
message.
I've noticed untyped actor has a "forward" feature , is this possible
for typed actor?