title: Akka: Stop actor after child actors are finished
body: <p>I often find myself using a "main" actor that creates a number of child actors for sub-tasks. When the sub-tasks are finished, the main actor should also stop himself. So I watch the child actors and stop the main actor when <code>context.children.isEmpty</code>. </p>
  
  <p>I often use this pattern, but as I never read about this. <strong>I am unsure, if this is a good idea or if there are problems with failing actors...?</strong> </p>
  
  <p>I have read about <a href="http://letitcrash.com/post/30165507578/shutdown-patterns-in-akka-2" rel="nofollow">Shutdown Patterns in Akka 2</a>, but this approach seems to be more complicated in Java than my solution?</p>
  
  <p>Here is my pseudo code for a main actor with two subtasks:</p>
  
  <pre><code>class MainActor extends AbstractActor {
  
      public MainActor() {
          receive(ReceiveBuilder
                  .match(SubTask1Response.class, this::handleSubTask1)
                  .match(SubTask2Response.class, this::handleSubTask2)
                  .match(Terminated.class, x -&gt; checkFinished())
                  .build());
      }
  
      @Override
      public void preStart() throws Exception {
          context().watch(context().actorOf(SubTask1Worker.props(), "subTask1"));
          context().watch(context().actorOf(SubTask2Worker.props(), "subTask2"));
      }
  
      private void checkFinished() {
          if(context().children().isEmpty()) {
              context().stop(self());
          }
      }
  
      // ...
  }
  </code></pre>
  
  <p>(I must use Java 8 :-(, but I am also happy to read Scala code if you can provide me another solution)</p>