Fehler in Shutdown-Logik für den `ExecutorService` korrigiert
[demos/kafka/training] / src / main / java / de / juplo / kafka / Application.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.boot.ApplicationArguments;
6 import org.springframework.boot.ApplicationRunner;
7 import org.springframework.boot.SpringApplication;
8 import org.springframework.boot.autoconfigure.SpringBootApplication;
9
10 import javax.annotation.PreDestroy;
11 import java.util.List;
12 import java.util.concurrent.ExecutorService;
13 import java.util.concurrent.TimeUnit;
14
15
16 @SpringBootApplication
17 @Slf4j
18 public class Application implements ApplicationRunner
19 {
20   @Autowired
21   EndlessConsumer endlessConsumer;
22   @Autowired
23   ExecutorService executor;
24
25
26   @Override
27   public void run(ApplicationArguments args) throws Exception
28   {
29     log.info("Starting EndlessConsumer");
30     endlessConsumer.start();
31   }
32
33   @PreDestroy
34   public void stopExecutor()
35   {
36     try
37     {
38       log.info("Shutting down the ExecutorService.");
39       executor.shutdown();
40       log.info("Waiting 5 seconds for the ExecutorService to terminate...");
41       executor.awaitTermination(5, TimeUnit.SECONDS);
42     }
43     catch (InterruptedException e)
44     {
45       log.error("Exception while waiting for the termination of the ExecutorService: {}", e.toString());
46     }
47     finally
48     {
49       if (!executor.isTerminated())
50       {
51         log.warn("Forcing shutdown of ExecutorService!");
52         executor
53             .shutdownNow()
54             .forEach(runnable -> log.warn("Unprocessed task: {}", runnable.getClass().getSimpleName()));
55       }
56       log.info("Shutdow of ExecutorService finished");
57     }
58   }
59
60
61   public static void main(String[] args)
62   {
63     SpringApplication.run(Application.class, args);
64   }
65 }