Skip to content

Commit

Permalink
Exits JVM after graceful shutdown
Browse files Browse the repository at this point in the history
* If shutdown was graceful jvm exits with code 0
* If shutdown was not graceful jvm exits with code -1

Signed-off-by: Klem Yannic (INST/ECS1) <[email protected]>
  • Loading branch information
Yannic92 authored and thjaeckle committed Jun 14, 2018
1 parent e2f4120 commit b72b37d
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;

import javax.annotation.concurrent.Immutable;
Expand All @@ -42,11 +46,13 @@
import akka.actor.ActorSystem;
import akka.actor.CoordinatedShutdown;
import akka.actor.Props;
import akka.actor.Scheduler;
import akka.cluster.Cluster;
import akka.cluster.pubsub.DistributedPubSub;
import akka.management.AkkaManagement;
import akka.management.cluster.bootstrap.ClusterBootstrap;
import akka.stream.ActorMaterializer;
import akka.stream.stage.TimerMessages;
import kamon.Kamon;

/**
Expand Down Expand Up @@ -173,6 +179,8 @@ protected void startActorSystem() {
startClusterMemberAwareActor(actorSystem, configReader);
startServiceRootActors(actorSystem, configReader);

final AtomicBoolean gracefulShutdown = new AtomicBoolean(false);

CoordinatedShutdown.get(actorSystem).addTask(
CoordinatedShutdown.PhaseBeforeServiceUnbind(), "Log shutdown initiation",
() -> {
Expand All @@ -184,8 +192,30 @@ protected void startActorSystem() {
CoordinatedShutdown.PhaseBeforeActorSystemTerminate(), "Log successful graceful shutdown",
() -> {
logger.info("Graceful shutdown completed.");
gracefulShutdown.set(true);
return CompletableFuture.completedFuture(Done.getInstance());
});

actorSystem.registerOnTermination(() -> {
if (gracefulShutdown.get()) {
exit(0);
} else {
exit(-1);
}
});
}

private void exit(int status) {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final String message = String.format("Exiting JVM with status code '%d'", status);
scheduler.schedule(() -> {
if(status == 0) {
logger.info(message);
}else {
logger.warn(message);
}
System.exit(status);
}, 0, TimeUnit.SECONDS);
}

/**
Expand Down

0 comments on commit b72b37d

Please sign in to comment.