/
SOQuestionGracefulShutdown.java
74 lines (60 loc) · 2.54 KB
/
SOQuestionGracefulShutdown.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class SOQuestionGracefulShutdown {
public static void main(String[] args) throws InterruptedException {
ScheduledThreadPoolExecutor taskExecutor = new ScheduledThreadPoolExecutor(2);
AtomicLong counter = new AtomicLong(0);
taskExecutor.scheduleWithFixedDelay(() -> {
try {
counter.incrementAndGet();
System.out.println("Task " + counter.get() + " started");
Thread.sleep(10_000);
System.out.println("Task " + counter.get() + " finished");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, 0, 1, TimeUnit.SECONDS);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
System.out.println("Shutting down");
taskExecutor.shutdown();
taskExecutor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}));
System.out.println("Started send a SIGTERM right after this message using: kill -15 " + ProcessHandle.current().pid());
for (; ; ) {
Thread.sleep(100);
}
}
public static void mainWithTaskExecutor(String[] args) throws InterruptedException {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(2);
taskExecutor.setMaxPoolSize(2);
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.initialize();
for (int i = 0; i < 3; i++) {
final int v = i;
taskExecutor.execute(() -> {
try {
Thread.sleep(10_000);
System.out.println("Task " + v + " completed");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
System.out.println("Shutting down");
taskExecutor.shutdown();
taskExecutor.getThreadPoolExecutor().awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}));
System.out.println("Jobs started, please send a SIGTERM right after this message using: kill -15 " + ProcessHandle.current().pid());
for (; ; ) {
Thread.sleep(100);
}
}
}