akka.actor.Terminated Java Examples

The following examples show how to use akka.actor.Terminated. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractMqttClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testTestConnection() {
    new TestKit(actorSystem) {{
        final Props props = createClientActor(getRef(), getConnection(false));
        final ActorRef mqttClientActor = watch(actorSystem.actorOf(props));

        mqttClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
        expectMsg(new Status.Success("successfully connected + initialized mapper"));
        expectDisconnectCalled();

        // client actor should be stopped after testing
        fishForMessage(FiniteDuration.apply(5L, TimeUnit.SECONDS), "client actor should stop after test",
                msg -> msg instanceof Terminated && ((Terminated) msg).getActor().equals(mqttClientActor));

        expectDisconnectCalled();
    }};
}
 
Example #2
Source File: ProcessReaper.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object message) {
	if (message instanceof Terminated) {
		try {
			Terminated term = (Terminated) message;
			String name = term.actor().path().toSerializationFormat();
			if (log != null) {
				log.error("Actor " + name + " terminated, stopping process...");

				// give the log some time to reach disk
				try {
					Thread.sleep(100);
				}
				catch (InterruptedException e) {
					// not really a problem if we don't sleep...
				}
			}
		}
		finally {
			System.exit(exitCode);
		}
	}
}
 
Example #3
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 6 votes vote down vote up
private void handle(Terminated message) {
	
	// Find the sender of this message
	final ActorRef sender = this.getSender();
	
	// Remove the sender from the watch list reaping its soul and terminate the entire actor system if this was its last actor
	if (this.watchees.remove(sender)) {
		this.log().info("Reaping {}.", sender);
		if (this.watchees.isEmpty()) {
			this.log().info("Every local actor has been reaped. Terminating the actor system...");
			this.getContext().getSystem().terminate();
		}
	} else {
		this.log().error("Got termination message from unwatched {}.", sender);
	}
}
 
Example #4
Source File: PubSubFactoryTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void watchForLocalActorTermination() {
    new TestKit(system2) {{
        final DistributedPub<String> pub = factory1.startDistributedPub();
        final DistributedSub sub = factory2.startDistributedSub();
        final TestProbe publisher = TestProbe.apply(system1);
        final TestProbe subscriber = TestProbe.apply(system2);
        watch(subscriber.ref());

        // GIVEN: a pub-sub channel is set up
        sub.subscribeWithAck(singleton("hello"), subscriber.ref()).toCompletableFuture().join();
        pub.publish("hello", publisher.ref());
        subscriber.expectMsg("hello");

        // WHEN: subscriber terminates
        system2.stop(subscriber.ref());
        expectMsgClass(Terminated.class);

        // THEN: the subscriber is removed
        Awaitility.await().untilAsserted(() ->
                assertThat(factory1.getSubscribers("hello").toCompletableFuture().join())
                        .describedAs("subscriber should be removed from ddata after termination")
                        .isEmpty()
        );
    }};
}
 
Example #5
Source File: CoffeeHouse.java    From oreilly-reactive-architecture-student with Apache License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder().
            match(CreateGuest.class, createGuest -> {
                final ActorRef guest = createGuest(createGuest.favoriteCoffee, createGuest.caffeineLimit);
                addGuestToBookkeeper(guest);
                context().watch(guest);
            }).
            match(ApproveCoffee.class, this::coffeeApproved, approveCoffee ->
                    barista.forward(new Barista.PrepareCoffee(approveCoffee.coffee, approveCoffee.guest), context())
            ).
            match(ApproveCoffee.class, approveCoffee -> {
                log().info("Sorry, {}, but you have reached your limit.", approveCoffee.guest.path().name());
                context().stop(approveCoffee.guest);
            }).
            match(Terminated.class, terminated -> {
                log().info("Thanks, {}, for being our guest!", terminated.getActor());
                removeGuestFromBookkeeper(terminated.getActor());
            }).build();
}
 
Example #6
Source File: CoffeeHouse.java    From oreilly-reactive-architecture-student with Apache License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder().
            match(CreateGuest.class, createGuest -> {
                final ActorRef guest = createGuest(createGuest.favoriteCoffee);
                addGuestToBookkeeper(guest);
                context().watch(guest);
            }).
            match(ApproveCoffee.class, this::coffeeApproved, approveCoffee ->
                    barista.forward(new Barista.PrepareCoffee(approveCoffee.coffee, approveCoffee.guest), context())
            ).
            match(ApproveCoffee.class, approveCoffee -> {
                log().info("Sorry, {}, but you have reached your limit.", approveCoffee.guest.path().name());
                context().stop(approveCoffee.guest);
            }).
            match(Terminated.class, terminated -> {
                log().info("Thanks, {}, for being our guest!", terminated.getActor());
                removeGuestFromBookkeeper(terminated.getActor());
            }).build();
}
 
Example #7
Source File: SessionManagerActor.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object msg) throws Exception {
  if (msg instanceof SessionAwareMsg) {
    forwardToSessionActor((SessionAwareMsg) msg);
  } else if (msg instanceof SessionTerminationMsg) {
    onSessionTermination((SessionTerminationMsg) msg);
  } else if (msg instanceof Terminated) {
    onTermination((Terminated) msg);
  } else if (msg instanceof SessionTimeoutMsg) {
    onSessionTimeout((SessionTimeoutMsg) msg);
  } else if (msg instanceof SessionCtrlMsg) {
    onSessionCtrlMsg((SessionCtrlMsg) msg);
  } else if (msg instanceof ClusterEventMsg) {
    broadcast(msg);
  }
}
 
Example #8
Source File: AppActor.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object msg) throws Exception {
  logger.debug("Received message: {}", msg);
  if (msg instanceof ToDeviceActorMsg) {
    processDeviceMsg((ToDeviceActorMsg) msg);
  } else if (msg instanceof ToAssetActorMsg) {
    processAssetMsg((ToAssetActorMsg) msg);
  } else if (msg instanceof ToPluginActorMsg) {
    onToPluginMsg((ToPluginActorMsg) msg);
  } else if (msg instanceof ToRuleActorMsg) {
    onToRuleMsg((ToRuleActorMsg) msg);
  } else if (msg instanceof ToDeviceActorNotificationMsg) {
    onToDeviceActorMsg((ToDeviceActorNotificationMsg) msg);
  } else if (msg instanceof Terminated) {
    processTermination((Terminated) msg);
  } else if (msg instanceof ClusterEventMsg) {
    broadcast(msg);
  } else if (msg instanceof ComponentLifecycleMsg) {
    onComponentLifecycleMsg((ComponentLifecycleMsg) msg);
  } else if (msg instanceof PluginTerminationMsg) {
    onPluginTerminated((PluginTerminationMsg) msg);
  } else {
    logger.warning("Unknown message: {}!", msg);
  }
}
 
Example #9
Source File: ProcessReaper.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object message) {
	if (message instanceof Terminated) {
		try {
			Terminated term = (Terminated) message;
			String name = term.actor().path().toSerializationFormat();
			if (log != null) {
				log.error("Actor " + name + " terminated, stopping process...");

				// give the log some time to reach disk
				try {
					Thread.sleep(100);
				}
				catch (InterruptedException e) {
					// not really a problem if we don't sleep...
				}
			}
		}
		finally {
			System.exit(exitCode);
		}
	}
}
 
Example #10
Source File: AkkaActorSystemTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void shutsDownOnActorFailure() {
	final ActorSystem actorSystem = AkkaUtils.createLocalActorSystem(new Configuration());

	try {
		final CompletableFuture<Terminated> terminationFuture = actorSystem.getWhenTerminated().toCompletableFuture();
		final ActorRef actorRef = actorSystem.actorOf(Props.create(SimpleActor.class));

		final FlinkException cause = new FlinkException("Flink test exception");

		actorRef.tell(Fail.exceptionally(cause), ActorRef.noSender());

		// make sure that the ActorSystem shuts down
		terminationFuture.join();
	} finally {
		AkkaUtils.terminateActorSystem(actorSystem).join();
	}
}
 
Example #11
Source File: SubUpdater.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(Subscribe.class, this::subscribe)
            .match(Unsubscribe.class, this::unsubscribe)
            .match(Terminated.class, this::terminated)
            .match(RemoveSubscriber.class, this::removeSubscriber)
            .matchEquals(Clock.TICK, this::tick)
            .match(SubscriptionsReader.class, this::updateSuccess)
            .match(Status.Failure.class, this::updateFailure)
            .matchAny(this::logUnhandled)
            .build();
}
 
Example #12
Source File: AkkaRpcServiceTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void shutdown() throws InterruptedException, ExecutionException, TimeoutException {
	final CompletableFuture<Void> rpcTerminationFuture = akkaRpcService.stopService();
	final CompletableFuture<Terminated> actorSystemTerminationFuture = FutureUtils.toJava(actorSystem.terminate());

	FutureUtils
		.waitForAll(Arrays.asList(rpcTerminationFuture, actorSystemTerminationFuture))
		.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);

	actorSystem = null;
	akkaRpcService = null;
}
 
Example #13
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
	return receiveBuilder()
			.match(WatchMeMessage.class, this::handle)
			.match(Terminated.class, this::handle)
			.matchAny(object -> this.log().error(this.getClass().getName() + " received unknown message: " + object.toString()))
			.build();
}
 
Example #14
Source File: SupervisorActorTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void completesTerminationFutureExceptionallyIfActorFails() throws Exception {
	final ActorSystem actorSystem = actorSystemResource.getActorSystem();

	final ActorRef supervisor = SupervisorActor.startSupervisorActor(actorSystem, actorSystem.getDispatcher());

	final SupervisorActor.ActorRegistration actorRegistration = startAkkaRpcActor(supervisor, "foobar");

	final CompletableFuture<Void> terminationFuture = actorRegistration.getTerminationFuture();
	assertThat(terminationFuture.isDone(), is(false));

	final CompletableFuture<Terminated> actorSystemTerminationFuture = actorSystem.getWhenTerminated().toCompletableFuture();

	final FlinkException cause = new FlinkException("Test cause.");
	actorRegistration.getActorRef().tell(Fail.exceptionally(cause), ActorRef.noSender());

	try {
		terminationFuture.get();
		fail("Expected the termination future being completed exceptionally");
	} catch (ExecutionException expected) {
		ExceptionUtils.findThrowable(expected, e -> e.equals(cause))
			.orElseThrow(() -> new FlinkException("Unexpected exception", expected));
	}

	// make sure that the supervisor actor has stopped --> terminating the actor system
	actorSystemTerminationFuture.join();
}
 
Example #15
Source File: Master.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
	return receiveBuilder()
			.match(StartMessage.class, this::handle)
			.match(BatchMessage.class, this::handle)
			.match(Terminated.class, this::handle)
			.match(RegistrationMessage.class, this::handle)
			.matchAny(object -> this.log().info("Received unknown message: \"{}\"", object.toString()))
			.build();
}
 
Example #16
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
	return receiveBuilder()
			.match(WatchMeMessage.class, this::handle)
			.match(Terminated.class, this::handle)
			.matchAny(object -> this.log().info("Received unknown message: \"{}\"", object.toString()))
			.build();
}
 
Example #17
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
private void handle(Terminated message) {
		final ActorRef sender = this.getSender();
		
		if (this.watchees.remove(sender)) {
//			this.log().info("Reaping {}", sender);
			
			if (this.watchees.isEmpty()) {
				this.log().info("Every local actor has been reaped. Terminating the actor system...");
				this.context().system().terminate();
			}
		} else {
			this.log().error("Got termination message from unwatched {}.", sender);
		}
	}
 
Example #18
Source File: Master.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
	return receiveBuilder()
			.match(EndMessage.class, this::handle)
			.match(Terminated.class, this::handle)
			.match(RegistrationMessage.class, this::handle)
			.matchAny(object -> this.log().info("Received unknown message: \"{}\"", object.toString()))
			.build();
}
 
Example #19
Source File: Master.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
protected void handle(Terminated message) {
	this.context().unwatch(message.getActor());
	this.workers.remove(message.getActor());
	
	if (this.workers.isEmpty())
		this.self().tell(PoisonPill.getInstance(), this.self());
}
 
Example #20
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
	return receiveBuilder()
			.match(WatchMeMessage.class, this::handle)
			.match(Terminated.class, this::handle)
			.matchAny(object -> this.log().info("Received unknown message: \"{}\"", object.toString()))
			.build();
}
 
Example #21
Source File: Reaper.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
private void handle(Terminated message) {
	final ActorRef sender = this.getSender();
	
	if (this.watchees.remove(sender)) {
		this.log().info("Reaping {}", sender);
		
		if (this.watchees.isEmpty()) {
			this.log().info("Every local actor has been reaped. Terminating the actor system...");
			this.context().system().terminate();
		}
	} else {
		this.log().error("Got termination message from unwatched {}.", sender);
	}
}
 
Example #22
Source File: AppActor.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private void processTermination(Terminated message) {
  ActorRef terminated = message.actor();
  if (terminated instanceof LocalActorRef) {
    logger.debug("Removed actor: {}", terminated);
  } else {
    throw new IllegalStateException("Remote actors are not supported!");
  }
}
 
Example #23
Source File: AbstractPersistenceSupervisor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void becomeActive(final ShutdownBehaviour shutdownBehaviour) {
    getContext().become(shutdownBehaviour.createReceive()
            .match(Terminated.class, this::childTerminated)
            .matchEquals(Control.START_CHILD, this::startChild)
            .matchEquals(Control.PASSIVATE, this::passivate)
            .matchAny(this::forwardToChildIfAvailable)
            .build());
}
 
Example #24
Source File: AbstractPersistenceSupervisor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void childTerminated(final Terminated message) {
    if (message.getAddressTerminated()) {
        log.error("Persistence actor for entity with ID <{}> terminated abnormally " +
                "because it crashed or because of network failure!", entityId);
    } else {
        log.warning("Persistence actor for entity with ID <{}> terminated abnormally.", entityId);
    }
    child = null;
    restartDelay = calculateRestartDelay();
    getTimers().startSingleTimer(Control.START_CHILD, Control.START_CHILD, restartDelay);
}
 
Example #25
Source File: Shepherd.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
private void handle(Terminated message) {
	
	// Find the sender of this message
	final ActorRef sender = this.getSender();
	
	// Remove the sender from the slaves list
	this.slaves.remove(sender);
}
 
Example #26
Source File: RpcEndpointTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void teardown() throws Exception {

	final CompletableFuture<Void> rpcTerminationFuture = rpcService.stopService();
	final CompletableFuture<Terminated> actorSystemTerminationFuture = FutureUtils.toJava(actorSystem.terminate());

	FutureUtils
		.waitForAll(Arrays.asList(rpcTerminationFuture, actorSystemTerminationFuture))
		.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
}
 
Example #27
Source File: AsyncCallsTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void shutdown() throws InterruptedException, ExecutionException, TimeoutException {
	final CompletableFuture<Void> rpcTerminationFuture = akkaRpcService.stopService();
	final CompletableFuture<Terminated> actorSystemTerminationFuture = FutureUtils.toJava(actorSystem.terminate());

	FutureUtils
		.waitForAll(Arrays.asList(rpcTerminationFuture, actorSystemTerminationFuture))
		.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
}
 
Example #28
Source File: SessionManagerActor.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private void onTermination(Terminated message) {
  ActorRef terminated = message.actor();
  if (terminated instanceof LocalActorRef) {
    log.info("Removed actor: {}.", terminated);
    // TODO: cleanup session actors map
  } else {
    throw new IllegalStateException("Remote actors are not supported!");
  }
}
 
Example #29
Source File: DefaultActorService.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@PreDestroy
public void stopActorSystem() {
  Future<Terminated> status = system.terminate();
  try {
    Terminated terminated = Await.result(status, Duration.Inf());
    log.info("Actor system terminated: {}", terminated);
  } catch (Exception e) {
    log.error("Failed to terminate actor system.", e);
  }
}
 
Example #30
Source File: Master.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
private void handle(Terminated message) {
	
	// Find the sender of this message
	final ActorRef sender = this.getSender();
	
	// Remove the sender from the scheduler
	this.schedulingStrategy.removeWorker(sender);
	
	this.log().warning("{} has terminated.", sender);
	
	// Check if work is complete and stop the actor hierarchy if true
	if (this.hasFinished()) {
		this.stopSelfAndListener();
	}
}