|
24 | 24 | import java.util.WeakHashMap;
|
25 | 25 | import java.util.concurrent.TimeUnit;
|
26 | 26 | import java.util.concurrent.TimeoutException;
|
| 27 | +import java.util.concurrent.atomic.AtomicBoolean; |
27 | 28 |
|
28 | 29 | import org.apache.commons.logging.Log;
|
29 | 30 | import org.apache.commons.logging.LogFactory;
|
@@ -59,33 +60,38 @@ class SpringApplicationShutdownHook implements Runnable {
|
59 | 60 |
|
60 | 61 | private final ApplicationContextClosedListener contextCloseListener = new ApplicationContextClosedListener();
|
61 | 62 |
|
62 |
| - private boolean inProgress; |
| 63 | + private final AtomicBoolean shutdownHookAdded = new AtomicBoolean(false); |
63 | 64 |
|
64 |
| - SpringApplicationShutdownHook() { |
65 |
| - try { |
66 |
| - addRuntimeShutdownHook(); |
67 |
| - } |
68 |
| - catch (AccessControlException ex) { |
69 |
| - // Not allowed in some environments |
70 |
| - } |
71 |
| - } |
72 |
| - |
73 |
| - protected void addRuntimeShutdownHook() { |
74 |
| - Runtime.getRuntime().addShutdownHook(new Thread(this, "SpringApplicationShutdownHook")); |
75 |
| - } |
| 65 | + private boolean inProgress; |
76 | 66 |
|
77 | 67 | SpringApplicationShutdownHandlers getHandlers() {
|
78 | 68 | return this.handlers;
|
79 | 69 | }
|
80 | 70 |
|
81 | 71 | void registerApplicationContext(ConfigurableApplicationContext context) {
|
| 72 | + addRuntimeShutdownHookIfNecessary(); |
82 | 73 | synchronized (SpringApplicationShutdownHook.class) {
|
83 | 74 | assertNotInProgress();
|
84 | 75 | context.addApplicationListener(this.contextCloseListener);
|
85 | 76 | this.contexts.add(context);
|
86 | 77 | }
|
87 | 78 | }
|
88 | 79 |
|
| 80 | + private void addRuntimeShutdownHookIfNecessary() { |
| 81 | + if (this.shutdownHookAdded.compareAndSet(false, true)) { |
| 82 | + addRuntimeShutdownHook(); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + void addRuntimeShutdownHook() { |
| 87 | + try { |
| 88 | + Runtime.getRuntime().addShutdownHook(new Thread(this, "SpringApplicationShutdownHook")); |
| 89 | + } |
| 90 | + catch (AccessControlException ex) { |
| 91 | + // Not allowed in some environments |
| 92 | + } |
| 93 | + } |
| 94 | + |
89 | 95 | @Override
|
90 | 96 | public void run() {
|
91 | 97 | Set<ConfigurableApplicationContext> contexts;
|
|
0 commit comments