junsid
junsid

Reputation: 355

how can i execute whole code in akka actor without using the Thread.sleep command?

i have a sample akka code

public class MainSystem {
  public static void main(String... args) throws Exception {
        final ActorSystem actorSystem = ActorSystem.create("actor-system");
        Thread.sleep(5000);
        final ActorRef actorRef = actorSystem.actorOf(SimpleActor.props(10));
        final ActorRef actorRef2 = actorSystem.actorOf(ActorTwo.props(10));
        System.out.println("actorref2:  "+actorRef2);

        actorRef2.tell(new Command("actor two cmd"), null);

        actorRef.tell(new Command("CMD 1"), null);
        actorRef.tell(new Command("CMD 2"), null);

        actorRef2.tell(new Command("actor two cmd   second"), null);


        actorRef.tell(new Command("CMD 3"), null);
        actorRef.tell(new Command("CMD 4"), null);
        actorRef.tell(new Command("CMD 5"), null);

        Thread.sleep(5000);

        actorSystem.shutdown();
    }
}

If i avoid the last sleep statement, the code will not execute completely. How can i write program to complete all codes in actor without using sleep ?

Upvotes: 0

Views: 123

Answers (1)

Johny T Koshy
Johny T Koshy

Reputation: 3922

You could shutdown the system from inside the actor after the last message is received and processed, and wait for termination usingactorSystem.awaitTermination().

Edit

Shut Down Patterns in Akka is a nice blog explaining a shutdown pattern. You may not need this much now, but you will get a gist. The code is in scala, but its not that complicated.

Upvotes: 2

Related Questions