20
20
import java .util .Collection ;
21
21
import java .util .Collections ;
22
22
import java .util .concurrent .CompletableFuture ;
23
+ import java .util .concurrent .Executors ;
24
+ import java .util .concurrent .ScheduledExecutorService ;
25
+ import java .util .concurrent .TimeUnit ;
26
+ import java .util .concurrent .atomic .AtomicBoolean ;
23
27
import java .util .function .Function ;
24
28
25
29
import javax .annotation .concurrent .Immutable ;
42
46
import akka .actor .ActorSystem ;
43
47
import akka .actor .CoordinatedShutdown ;
44
48
import akka .actor .Props ;
49
+ import akka .actor .Scheduler ;
45
50
import akka .cluster .Cluster ;
46
51
import akka .cluster .pubsub .DistributedPubSub ;
47
52
import akka .management .AkkaManagement ;
48
53
import akka .management .cluster .bootstrap .ClusterBootstrap ;
49
54
import akka .stream .ActorMaterializer ;
55
+ import akka .stream .stage .TimerMessages ;
50
56
import kamon .Kamon ;
51
57
52
58
/**
@@ -173,6 +179,8 @@ protected void startActorSystem() {
173
179
startClusterMemberAwareActor (actorSystem , configReader );
174
180
startServiceRootActors (actorSystem , configReader );
175
181
182
+ final AtomicBoolean gracefulShutdown = new AtomicBoolean (false );
183
+
176
184
CoordinatedShutdown .get (actorSystem ).addTask (
177
185
CoordinatedShutdown .PhaseBeforeServiceUnbind (), "Log shutdown initiation" ,
178
186
() -> {
@@ -184,8 +192,30 @@ protected void startActorSystem() {
184
192
CoordinatedShutdown .PhaseBeforeActorSystemTerminate (), "Log successful graceful shutdown" ,
185
193
() -> {
186
194
logger .info ("Graceful shutdown completed." );
195
+ gracefulShutdown .set (true );
187
196
return CompletableFuture .completedFuture (Done .getInstance ());
188
197
});
198
+
199
+ actorSystem .registerOnTermination (() -> {
200
+ if (gracefulShutdown .get ()) {
201
+ exit (0 );
202
+ } else {
203
+ exit (-1 );
204
+ }
205
+ });
206
+ }
207
+
208
+ private void exit (int status ) {
209
+ final ScheduledExecutorService scheduler = Executors .newScheduledThreadPool (1 );
210
+ final String message = String .format ("Exiting JVM with status code '%d'" , status );
211
+ scheduler .schedule (() -> {
212
+ if (status == 0 ) {
213
+ logger .info (message );
214
+ }else {
215
+ logger .warn (message );
216
+ }
217
+ System .exit (status );
218
+ }, 0 , TimeUnit .SECONDS );
189
219
}
190
220
191
221
/**
0 commit comments