private void finishCommit( @Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) { LOG.debug( "{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID()); try { cohortEntry.commit(); sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf()); shardMBean.incrementCommittedTransactionCount(); shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis()); } catch (Exception e) { sender.tell(new akka.actor.Status.Failure(e), getSelf()); LOG.error( "{}, An exception occurred while committing transaction {}", persistenceId(), transactionID, e); shardMBean.incrementFailedTransactionsCount(); } finally { commitCoordinator.currentTransactionComplete(transactionID, true); } }
@SuppressWarnings("deprecation") public static void main(String[] args) { ActorSystem system = ActorSystem.create("MySystem"); ActorRef myActor = system.actorOf(new Props(MyUntypedActor.class), "myactor"); myActor.tell("hello"); System.out.println(Thread.currentThread().getId() + " World"); }
public void constructGraph(ActorRef[] nodes, ActorRef master) { for (int i = 0; i < nodes.length; i++) { ActorRef worker = nodes[i]; InitializeMessage message = new InitializeMessage(nodes, master); worker.tell(message); } }
@Test public void receiveTimeout() { ActorSystem system = ActorSystem.create("MySystem"); ActorRef myActor = system.actorOf(new Props(MyReceivedTimeoutUntypedActor.class)); myActor.tell("Hello", null); system.shutdown(); }
@Test public void useLoggingActorWithMDC() { ActorSystem system = ActorSystem.create("MyDiagnosticSystem"); ActorRef mdcActor = system.actorOf(Props.create(MdcActor.class, this)); mdcActor.tell("some request", ActorRef.noSender()); JavaTestKit.shutdownActorSystem(system); }
protected void createGuest(int count, Drink drink, int maxDrinkCount) { IntStream.range(0, count) .forEach( c -> { bar.tell(new CocktailBar.CreateGuest(drink, maxDrinkCount), ActorRef.noSender()); }); }
public void doReceive(Object message) { if (message instanceof StartMessage) { doingNum++; } else if (message instanceof SuccessMessage) { finishNum++; if (isAllSend && doingNum == finishNum) { listener.tell( new FileEncodingCheckResultMessage( fileEncodingMessage.file, fileEncodingMessage.index, fileEncodingMessage.encoding, true)); // getContext().stop(getSelf()); } } else if (message instanceof FailMessage) { listener.tell( new FileEncodingCheckResultMessage( fileEncodingMessage.file, fileEncodingMessage.index, fileEncodingMessage.encoding, false)); // getContext().stop(getSelf()); } else if (message instanceof AllStartedMessage) { isAllSend = true; } else { unhandled(message); } }
public static void main(String[] args) { ActorRef actorARef = Actors.actorOf(ActorA.class); SupervisorFactory factory = new SupervisorFactory( new SupervisorConfig( new OneForOneStrategy(new Class[] {IllegalArgumentException.class}, 3, 5000), new Supervise[] {new Supervise(actorARef, permanent())})); Supervisor supervisor = factory.newInstance(); supervisor.start(); actorARef.tell(new Message("message1 before crash")); actorARef.tell(new Message("message2 before crash")); // let actorA crash actorARef.tell(new CrashMessage()); actorARef.tell(new Message("message3 after crash")); try { Thread.sleep(1000); } catch (InterruptedException e) { } supervisor.shutdown(); }
/** * *************************************************************************** BEGIN: Methods to * handle specificActor communication * * <p>taken from original communication pattern from Alex * *************************************************************************** */ public static void answerSpecificActor(BasicActor gridActor, ActorRef sender) { if (!gridActor.detectCircle()) { gridActor.reportToParentEnabled = false; sender.tell( new DirectAnswerMessage(gridActor.getCurrentTimeStep(), gridActor.upStreamTrace, 0.0), gridActor.getSelf()); } else { gridActor.reportToParentEnabled = true; sender.tell( new DirectAnswerMessage(gridActor.getCurrentTimeStep(), gridActor.upStreamTrace, 0.0), gridActor.getSelf()); BasicAnswer basicAnswer = new BasicAnswer( gridActor.getCurrentTimeStep(), gridActor.upStreamTrace, true, false, gridActor.getSelf().path().toString(), gridActor.answerContent); gridActor.getContext().parent().tell(basicAnswer, gridActor.getSelf()); } }
public static void main(String[] args) throws Exception { ActorSystem _system = ActorSystem.create("BecomeUnbecome"); ActorRef atorPrincipal = _system.actorOf(new Props(Principal.class), "principal"); atorPrincipal.tell("2"); Thread.sleep(2000); _system.shutdown(); }
@Test public void useLoggingActor() { ActorSystem system = ActorSystem.create("MySystem"); ActorRef myActor = system.actorOf(Props.create(MyActor.class, this)); myActor.tell("test", ActorRef.noSender()); JavaTestKit.shutdownActorSystem(system); }
private void closeActor() { if (slaveActorRef != null) { slaveActorRef.tell(new UnregisterSlaveMountPoint(), ActorRef.noSender()); slaveActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); slaveActorRef = null; } }
public void onReceive(Object message) throws Exception { System.out.println("----------------------------------------------------------"); if (getSender().equals(getContext().parent())) { System.out.println("-A-" + getSender()); // == getContext().parent() System.out.println("-A-" + getSelf()); System.out.println("-A-" + getContext().self()); System.out.println("-A-" + getContext().parent()); if (message instanceof JsonNode) { System.out.println("-A-" + "GO!"); JsonNode event = (JsonNode) message; models.ChatRoom.defaultRoom.tell( new Talk(username, event.get("text").asText()), getSender()); } else { unhandled(message); } } else { System.out.println("-B-" + getSender()); System.out.println("-B-" + getSelf()); System.out.println("-B-" + getContext().self()); System.out.println("-B-" + getContext().parent()); if (message instanceof ObjectNode) { System.out.println("-B-" + "GO!"); // JsonNode event = (JsonNode)message; out.tell(message, ActorRef.noSender()); } else { unhandled(message); } } }
@Test public void testTcpWorkerDupAndCancel() { ActorRef asyncWorker = null; logger.info("IN testTcpWorkerDupAndCancel"); try { // Start new job int actorMaxOperationTimeoutSec = 15; asyncWorker = ActorConfig.createAndGetActorSystem() .actorOf( Props.create( TcpWorker.class, actorMaxOperationTimeoutSec, getTcpMetaSample(), LOCALHOST)); final FiniteDuration duration = Duration.create(20, TimeUnit.SECONDS); Future<Object> future = Patterns.ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST, new Timeout(duration)); // test dup asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, asyncWorker); // test cancel asyncWorker.tell(RequestWorkerMsgType.CANCEL, asyncWorker); ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await.result(future, duration); logger.info("\nWorker response:" + response.toString()); } catch (Throwable ex) { logger.error("Exception in test : " + ex); } } // end func
public void testSchedule( final JavaTestKit probe, Props props, FiniteDuration startDuration, FiniteDuration afterRestartDuration) { Iterable<akka.testkit.EventFilter> filter = Arrays.asList( new akka.testkit.EventFilter[] { (akka.testkit.EventFilter) new ErrorFilter(ArithmeticException.class) }); try { system.eventStream().publish(new Mute(filter)); final ActorRef actor = system.actorOf(props); new Within(startDuration) { protected void run() { probe.expectMsgEquals("tick"); probe.expectMsgEquals("tick"); probe.expectMsgEquals("tick"); } }; actor.tell("restart", getRef()); new Within(afterRestartDuration) { protected void run() { probe.expectMsgEquals("tick"); probe.expectMsgEquals("tick"); } }; system.stop(actor); } finally { system.eventStream().publish(new UnMute(filter)); } }
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 } }
@Test public void serializeActorRefs() { final ActorSystem theActorSystem = ActorSystem.create("whatever"); final ActorRef theActorRef = theActorSystem.deadLetters(); // Of course this should be you // #actorref-serializer // Serialize // (beneath toBinary) final Address transportAddress = Serialization.currentTransportAddress().value(); String identifier; // If there is no transportAddress, // it means that either this Serializer isn't called // within a piece of code that sets it, // so either you need to supply your own, // or simply use the local path. if (transportAddress == null) identifier = theActorRef.path().toString(); else identifier = theActorRef.path().toStringWithAddress(transportAddress); // Then just serialize the identifier however you like // Deserialize // (beneath fromBinary) final ActorRef deserializedActorRef = theActorSystem.actorFor(identifier); // Then just use the ActorRef // #actorref-serializer theActorSystem.shutdown(); }
@Override public void preStart() throws Exception { log.info("Starting TaskStorage"); clusterProxy = context().system().actorFor(ActorSystemHolder.CLUSTER_PROXY_PATH); ActorRef mediator = DistributedPubSub.get(getContext().system()).mediator(); mediator.tell(new DistributedPubSubMediator.Subscribe(TOPIC, self()), self()); }
private void sendMessages(ActorSystem system) { ActorRef service = getService(system); for (int i = 0; i < 200; i++) { service.tell(new Bet("ready_player_one", i % 10 + 1, i % 100 + 1)); } System.out.println("*** SENDING OK"); }
/* initial statistics used for calculating word metadata such as word vectors to train on */ protected void calcWordFrequencies() { numFiles = countFiles(); CountDownLatch latch = new CountDownLatch(numFiles); ActorRef fileActor = system.actorOf( new RoundRobinPool(Runtime.getRuntime().availableProcessors()) .props(Props.create(VocabCreatorActor.class, this, latch))); for (File f : rootDir.listFiles()) { File[] subFiles = f.listFiles(); if (f.isFile()) fileActor.tell(f, fileActor); else if (subFiles != null) for (File doc : subFiles) { if (!doc.isFile()) continue; fileActor.tell(doc, fileActor); } } try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } log.info("Done calculating word frequencies"); }
@Test public void test() throws InterruptedException { final ActorSystem system = ActorSystem.create("helloakka"); final ActorRef akkaBot = system.actorOf(Props.create(AkkaBotMaster.class), "master"); System.out.println("JavaBotMain Actor System was created"); akkaBot.tell(3, ActorRef.noSender()); Thread.sleep(100); }
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); } }
@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 public void onReceive(Object message) throws Exception { if (message instanceof Tcp.Received) { ByteString data = ((Tcp.Received) message).data(); connection.tell(TcpMessage.write(data, new Ack()), getSelf()); } else if (message instanceof Ack) { connection.tell(TcpMessage.resumeReading(), getSelf()); } }
@Test public void contextActorOf() { // #context-actorOf ActorSystem system = ActorSystem.create("MySystem"); ActorRef myActor = system.actorOf(new Props(MyUntypedActor.class), "myactor"); // #context-actorOf myActor.tell("test", null); system.shutdown(); }
private void handleRequest(JoinRequest req) { Collection<ActorRef> others = new ArrayList<>(this.others); others.add(self()); req.getActor().tell(new JoinAck(others, null), self()); for (ActorRef other : this.others) { other.tell(new NewMember(req.getActor(), req.getUsername()), self()); } this.others.add(req.getActor()); }
@Test public void useKill() { ActorSystem system = ActorSystem.create("MySystem"); ActorRef victim = system.actorOf(new Props(MyUntypedActor.class)); // #kill victim.tell(Kill.getInstance(), null); // #kill system.shutdown(); }
private void observe(final Object message) { final ActorRef self = self(); final Observe request = (Observe) message; final ActorRef observer = request.observer(); if (observer != null) { observers.add(observer); observer.tell(new Observing(self), self); } }
@Override public void execute(final Object message) throws Exception { // Notify the observers. final MediaGroupStateChanged event = new MediaGroupStateChanged(MediaGroupStateChanged.State.ACTIVE); for (final ActorRef observer : observers) { observer.tell(event, source); } }
@Override protected synchronized void removeRegistration() { if (listenerRegistrationActor != null) { listenerRegistrationActor.tell( CloseDataTreeChangeListenerRegistration.getInstance(), ActorRef.noSender()); listenerRegistrationActor = null; } dataChangeListenerActor.tell(PoisonPill.getInstance(), ActorRef.noSender()); }