1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.rmi;
19
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;
25
26
27
28
29
30
31 final class ShutdownHookSupport {
32 private static final List<Thread> HOOKS = ("true".equals(System.getProperty(
33 "org.newsclub.net.unix.rmi.collect-shutdown-hooks", "false"))) ? new ArrayList<>() : null;
34
35
36
37
38
39
40
41
42
43 public static Thread addWeakShutdownHook(ShutdownHook hook) {
44 Thread t = new ShutdownThread(new WeakReference<>(hook));
45 Runtime.getRuntime().addShutdownHook(t);
46 if (HOOKS != null) {
47 synchronized (HOOKS) {
48 HOOKS.add(t);
49 }
50 }
51 return t;
52 }
53
54
55 @SuppressFBWarnings({"RU_INVOKE_RUN"})
56 @SuppressWarnings("DoNotCall" )
57 static void runHooks() {
58 if (HOOKS != null) {
59 List<Thread> list;
60 synchronized (HOOKS) {
61 list = new ArrayList<>(HOOKS);
62 HOOKS.clear();
63 }
64 for (Thread t : list) {
65 t.run();
66 }
67 }
68 }
69
70
71
72
73
74
75 interface ShutdownHook {
76
77
78
79
80
81
82
83
84
85
86
87
88 @SuppressFBWarnings("THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION")
89 void onRuntimeShutdown(Thread thread) throws Exception;
90 }
91
92
93
94
95
96
97 static final class ShutdownThread extends Thread {
98 private final WeakReference<ShutdownHook> ref;
99
100 ShutdownThread(WeakReference<ShutdownHook> ref) {
101 super();
102 this.ref = ref;
103 }
104
105 @Override
106 public void run() {
107 ShutdownHook hook = ref.get();
108 ref.clear();
109 try {
110 if (hook != null) {
111 hook.onRuntimeShutdown(this);
112 }
113 } catch (Exception e) {
114
115 }
116 }
117 }
118 }