Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Custom Akka Supervisor in Java

Tags:

java

akka

I'm trying to implement jobs with retry semantics using Akka. If a worker fails (throws an exception) during its job, in addition to restarting it I want to resubmit the job it was working on.

The approach I'm trying is a custom supervisor, but I can't get it to restart the worker on failure. e.g. Run the following code with Akka 1.1.3, and you'll never see the restart messages:

  import akka.actor.ActorRef;
  import akka.actor.UntypedActor;
  import akka.actor.UntypedActorFactory;
  import akka.config.Supervision;

  import static akka.actor.Actors.actorOf;
  import static java.lang.System.out;

  public class Supervisor extends UntypedActor {
      private ActorRef worker;

      public static class Worker extends UntypedActor {
          @Override
          public void onReceive(Object message) {
              throw new RuntimeException("croak");
          }

          public void preRestart(Object reason) {
              out.println("supervisor is restarting me!");
          }

          public void postRestart(Object reason) {
              out.println("supervisor restarted me.");
          }
      }

      public static void main(String[] args) {
          ActorRef supervisor = actorOf(new UntypedActorFactory() {
              public UntypedActor create() {
                  return new Supervisor();
              }
          });

          supervisor.start();
          supervisor.sendOneWay("job");
      }

      @Override
      public void preStart() {
          getContext().setFaultHandler(new Supervision.OneForOneStrategy(
              new Class[]{RuntimeException.class},
              3,
              1000
          ));

          // why doesn't the compiler like this line?
          // worker = actorOf(Worker.class);

          worker = actorOf(new UntypedActorFactory() {
              public UntypedActor create() {
                  return new Worker();
              }
          });

          getContext().startLink(worker);
      }

      @Override
      public void onReceive(Object message) {
          worker.sendOneWay(message);
      }
  }

Any idea what I'm doing wrong?

Thanks!

like image 326
spieden Avatar asked Aug 15 '11 19:08

spieden


1 Answers

These are the correct signatures for restart methods in Worker actor:

    @Override
    public void preRestart(Throwable reason) {
        out.println("supervisor is restarting me!");
    }

    @Override
    public void postRestart(Throwable reason) {
        out.println("supervisor restarted me.");
    }

And I'm not getting any compilation error for the commented-out line.

like image 168
denis.solonenko Avatar answered Oct 01 '22 23:10

denis.solonenko