private void closeActor() {
   if (slaveActorRef != null) {
     slaveActorRef.tell(new UnregisterSlaveMountPoint(), ActorRef.noSender());
     slaveActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
     slaveActorRef = null;
   }
 }
 public void preStart() {
   try {
     System.out.println("=================================================");
     final Timeout timeout = new Timeout(Duration.create(1, SECONDS));
     Future<Object> rt =
         Patterns.ask(models.ChatRoom.defaultRoom, new Join(username, out), timeout);
     String result = (String) Await.result(rt, timeout.duration());
     System.out.println("-O-" + getSender());
     System.out.println("-O-" + getSelf());
     System.out.println("-O-" + getContext().self());
     System.out.println("-O-" + getContext().parent());
     if ("OK".equals(result)) {
       System.out.println("OK!");
       // go!
     } else {
       // Cannot connect, create a Json error.
       ObjectNode error = Json.newObject();
       error.put("error", result);
       // Send the error to the socket.
       out.tell(error, null);
       System.out.println("ERROR!");
       // getContext().parent().tell(PoisonPill.getInstance(), self());
       out.tell(PoisonPill.getInstance(), self());
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     // force to stop actor
   }
 }
 @Override
 void onEmptySetOfAsynchronousActions() {
   if (state == State.ALL_OUTPUTS) {
     state = State.DONE;
     getSelf().tell(PoisonPill.getInstance(), getSelf());
   }
 }
Example #4
0
 public void onReceive(Object message) {
   if (message.equals("job")) {
     worker.tell("crunch", getSelf());
   } else if (message.equals(SHUTDOWN)) {
     worker.tell(PoisonPill.getInstance(), getSelf());
     getContext().become(shuttingDown);
   }
 }
  private void closeTransaction(boolean sendReply) {
    getDOMStoreTransaction().abort();

    if (sendReply && returnCloseTransactionReply()) {
      getSender().tell(new CloseTransactionReply(), getSelf());
    }

    getSelf().tell(PoisonPill.getInstance(), getSelf());
  }
 @Test
 public void usePoisonPill() {
   ActorSystem system = ActorSystem.create("MySystem");
   ActorRef myActor = system.actorOf(new Props(MyUntypedActor.class));
   // #poison-pill
   myActor.tell(PoisonPill.getInstance(), null);
   // #poison-pill
   system.shutdown();
 }
  @Override
  protected synchronized void removeRegistration() {
    if (listenerRegistrationActor != null) {
      listenerRegistrationActor.tell(
          CloseDataTreeChangeListenerRegistration.getInstance(), ActorRef.noSender());
      listenerRegistrationActor = null;
    }

    dataChangeListenerActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
  }
  public static Address startBackend(Address joinAddress, String role) {
    Config conf =
        ConfigFactory.parseString("akka.cluster.roles=[" + role + "]")
            .withFallback(ConfigFactory.load());
    ActorSystem system = ActorSystem.create(systemName, conf);
    Address realJoinAddress =
        (joinAddress == null) ? Cluster.get(system).selfAddress() : joinAddress;
    Cluster.get(system).join(realJoinAddress);

    system.actorOf(
        ClusterSingletonManager.defaultProps(
            Master.props(workTimeout), "active", PoisonPill.getInstance(), role),
        "master");

    return realJoinAddress;
  }
Example #9
0
  /**
   * Shuts down the checkpoint coordinator.
   *
   * <p>After this method has been called, the coordinator does not accept and further messages and
   * cannot trigger any further checkpoints.
   */
  public void shutdown() throws Exception {
    synchronized (lock) {
      try {
        if (!shutdown) {
          shutdown = true;
          LOG.info("Stopping checkpoint coordinator for job " + job);

          periodicScheduling = false;
          triggerRequestQueued = false;

          // shut down the thread that handles the timeouts and pending triggers
          timer.cancel();

          // make sure that the actor does not linger
          if (jobStatusListener != null) {
            jobStatusListener.tell(PoisonPill.getInstance());
            jobStatusListener = null;
          }

          checkpointIdCounter.stop();

          // clear and discard all pending checkpoints
          for (PendingCheckpoint pending : pendingCheckpoints.values()) {
            pending.discard(userClassLoader);
          }
          pendingCheckpoints.clear();

          // clean and discard all successful checkpoints
          completedCheckpointStore.discardAllCheckpoints();

          onShutdown();
        }
      } finally {
        // Remove shutdown hook to prevent resource leaks, unless this is invoked by the
        // shutdown hook itself.
        if (shutdownHook != null && shutdownHook != Thread.currentThread()) {
          try {
            Runtime.getRuntime().removeShutdownHook(shutdownHook);
          } catch (IllegalStateException ignored) {
            // race, JVM is in shutdown already, we can safely ignore this
          } catch (Throwable t) {
            LOG.warn("Error unregistering checkpoint coordinator shutdown hook.", t);
          }
        }
      }
    }
  }
Example #10
0
  public static void main(String[] args) throws Exception {

    ApplicationContext context = SpringApplication.run(App.class, args);

    ActorSystem system = context.getBean(ActorSystem.class);

    final LoggingAdapter log = Logging.getLogger(system, App.class.getSimpleName());

    log.info("Starting up");

    SpringExtension ext = context.getBean(SpringExtension.class);

    // Use the Spring Extension to create props for a named actor bean
    ActorRef calculator =
        system.actorOf(ext.props("calculator").withMailbox("akka.priority-mailbox"));

    /*
     * Create a completion service instance to await all futures
     */
    final ExecutionContext ec = system.dispatcher();

    Timeout timeout = new Timeout(120, TimeUnit.SECONDS);
    List<Long> ids = new ArrayList<>();

    ArrayList<Future<Object>> futures = new ArrayList<Future<Object>>();

    for (int i = 1; i <= 10; i++) {
      Future<Object> future = Patterns.ask(calculator, new CompilationRequest(i + " + 5"), timeout);
      future.onSuccess(
          new OnSuccess<Object>() {
            public void onSuccess(Object result) {
              if (result instanceof CompilationResult) {
                synchronized (ids) {
                  log.debug("Compilation result {} ", result.toString());
                  ids.add(((CompilationResult) result).getExpressionId());
                }
              } else {
                log.info("Compilation result is unknown type {} ", result.toString());
              }
            }
          },
          ec);
      futures.add(future);
    }

    Future<Iterable<Object>> seq = Futures.sequence(futures, ec);
    Await.result(seq, Duration.create(30, SECONDS));
    log.info("======================================================");
    log.info("Done waiting for compilations...{} ids", ids.size());
    log.info("======================================================");
    futures.clear();

    long start = System.nanoTime();
    List<Double> results = new ArrayList<>();

    Long count = 1_000_000L;
    for (long i = 1; i <= count; i++) {
      Future<Object> future =
          Patterns.ask(
              calculator,
              new CalculationRequest(i, ids.get((int) (i % ids.size())), null),
              timeout);
      future.onSuccess(
          new OnSuccess<Object>() {
            public void onSuccess(Object result) {
              if (result instanceof CalculationResult) {
                log.debug("Calculation result {} ", result.toString());
                //						synchronized(results)
                //						{
                //							results.add((Double) ((CalculationResult) result).getValue());
                //						}
              } else {
                log.info("Calculation result is unknown type {} ", result.toString());
              }
            }
          },
          ec);
      futures.add(future);
    }
    seq = Futures.sequence(futures, ec);
    Await.result(seq, Duration.create(600, SECONDS));
    calculator.tell(PoisonPill.getInstance(), null);

    while (!calculator.isTerminated()) {
      Thread.sleep(100);
    }

    long end = System.nanoTime();
    //        //int count = context.getBean(JdbcTemplate.class).queryForObject("SELECT COUNT(*) FROM
    // tasks", Integer.class);
    Long elapsed = TimeUnit.MILLISECONDS.convert((end - start), TimeUnit.NANOSECONDS);
    Double tps = count.doubleValue() / (elapsed.doubleValue() / Double.parseDouble("1000"));
    log.info("{} calculations in {}ms {}tps", count, elapsed, tps);
    log.info("Shutting down ------------------------------> {}", results.size());
    Thread.sleep(10000);
    system.shutdown();
    system.awaitTermination();
  }
Example #11
0
  @Override
  public void onReceive(Object message) throws Exception {
    LOGGER.info(getSelf() + " : Receives from " + getSender() + " message " + message);
    try {
      // handle children
      /**
       * Get TopupRequest, send TopupRequest to slave actors After 5 consecutive requests, check
       * balance of account
       */
      if (message instanceof TopupRequest) {
        router.tell(message, getSelf());
        ++numberOfRequestMessages;
        if (numberOfRequestMessages >= config.getNumberOfConsicutiveRequests()) {

          router.tell(new BalanceRequest(), getSelf());
          numberOfRequestMessages = 0;
        }
      }
      /**
       * Receive the CheckUnknownRequest. Get all the unknown XPAY transactions and send it to
       * slaves for confirmation.
       */
      else if (message instanceof CheckUnknownRequest) {
        List<AtTransaction> pendingTransactions =
            mapper.searchTransactionByStatusAndConnType("UNKNOWN", "XPAY");
        Date now = new Date();
        for (AtTransaction transaction : pendingTransactions) {
          long diff = now.getTime() - transaction.getUpdated_date().getTime();
          if (diff < 24 * MILITOHOURCONVERSION) {
            router.tell(transaction, getSelf());
          } else {
            transaction.setTxn_status("SUCCESS");
            getSelf().tell(transaction);
          }
        }
      }

      /** Handle the Query Balance result. Update new balance in database */
      else if (message instanceof BalanceResponse) {
        BalanceResponse response = (BalanceResponse) message;
        mapper.UpdateBalance(response);
      }
      /** Update the transactions to database */
      else if (message instanceof AtTransaction) {
        AtTransaction transaction = (AtTransaction) message;
        transaction.setUpdated_by("XPAY_SYS");
        transaction.setUpdated_date(new Date());
        if (transaction.getError_code() == null) {
          transaction.setError_code("");
        }
        mapper.UpdateTxn(transaction);
      }
      /** Kill self and all the children */
      else if (message instanceof Stop) {
        router.tell(PoisonPill.getInstance());
        getContext().stop(getSelf());
      }
    } catch (Exception e) {
      LOGGER.error(getSelf(), e);
    }
  }
Example #12
0
 protected void closeTransaction(CloseTransaction message) {
   transaction.close();
   getSender().tell(new CloseTransactionReply().toSerializable(), getSelf());
   getSelf().tell(PoisonPill.getInstance(), getSelf());
 }
Example #13
0
  public WebsocketTransport(Messages.JoinWebsocket join) {
    this.out = join.out;
    this.in = join.in;
    this.context = join.context;

    final ActorRef self = getContext().self();

    in.onClose(
        () -> {
          signalJActor.tell(new Messages.Quit(context.connectionId), self);
          self.tell(PoisonPill.getInstance(), self);
        });
    in.onMessage(
        json -> {
          Logger.debug("Message from user: "******" : " + json);
          signalJActor.tell(new Messages.Execute(context, json), self);
        });

    context()
        .setReceiveTimeout(
            Duration.create(
                SignalJPlugin.getConfiguration().getKeepAliveTimeout() / 2, TimeUnit.SECONDS));

    receive(
        ReceiveBuilder.match(
                Messages.JoinWebsocket.class, r -> out.write(JsonHelper.writeConnect(prefix)))
            .match(
                Messages.MethodReturn.class,
                methodReturn -> {
                  out.write(JsonHelper.writeMethodReturn(methodReturn));
                  sendAck(methodReturn);
                })
            .match(
                Messages.ClientFunctionCall.class,
                clientFunctionCall -> {
                  out.write(JsonHelper.writeClientFunctionCall(clientFunctionCall, prefix));
                  sendAck(clientFunctionCall);
                })
            .match(
                Messages.ClientCallEnd.class,
                clientCallEnd -> {
                  out.write(JsonHelper.writeConfirm(clientCallEnd.context));
                  sendAck(clientCallEnd);
                })
            .match(ReceiveTimeout.class, r -> out.write(JsonHelper.writeHeartbeat()))
            .match(
                Messages.ReconnectWebsocket.class,
                r -> Logger.debug("Reconnect Websocket " + r.context.connectionId))
            .match(
                Messages.StateChange.class,
                state -> {
                  out.write(JsonHelper.writeState(state));
                  sendAck(state);
                })
            .match(
                Messages.Error.class,
                error -> {
                  out.write(JsonHelper.writeError(error));
                  sendAck(error);
                })
            .build());
  }