1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.util.thread;
20
21 import java.util.Arrays;
22 import java.util.List;
23 import java.util.concurrent.CopyOnWriteArrayList;
24
25 import org.eclipse.jetty.util.component.Destroyable;
26 import org.eclipse.jetty.util.component.LifeCycle;
27 import org.eclipse.jetty.util.log.Log;
28 import org.eclipse.jetty.util.log.Logger;
29
30
31
32
33
34
35
36
37
38 public class ShutdownThread extends Thread
39 {
40 private static final Logger LOG = Log.getLogger(ShutdownThread.class);
41 private static final ShutdownThread _thread = new ShutdownThread();
42
43 private boolean _hooked;
44 private final List<LifeCycle> _lifeCycles = new CopyOnWriteArrayList<LifeCycle>();
45
46
47
48
49
50
51
52 private ShutdownThread()
53 {
54 }
55
56
57 private synchronized void hook()
58 {
59 try
60 {
61 if (!_hooked)
62 Runtime.getRuntime().addShutdownHook(this);
63 _hooked=true;
64 }
65 catch(Exception e)
66 {
67 LOG.ignore(e);
68 LOG.info("shutdown already commenced");
69 }
70 }
71
72
73 private synchronized void unhook()
74 {
75 try
76 {
77 _hooked=false;
78 Runtime.getRuntime().removeShutdownHook(this);
79 }
80 catch(Exception e)
81 {
82 LOG.ignore(e);
83 LOG.debug("shutdown already commenced");
84 }
85 }
86
87
88
89
90
91
92
93 public static ShutdownThread getInstance()
94 {
95 return _thread;
96 }
97
98
99 public static synchronized void register(LifeCycle... lifeCycles)
100 {
101 _thread._lifeCycles.addAll(Arrays.asList(lifeCycles));
102 if (_thread._lifeCycles.size()>0)
103 _thread.hook();
104 }
105
106
107 public static synchronized void register(int index, LifeCycle... lifeCycles)
108 {
109 _thread._lifeCycles.addAll(index,Arrays.asList(lifeCycles));
110 if (_thread._lifeCycles.size()>0)
111 _thread.hook();
112 }
113
114
115 public static synchronized void deregister(LifeCycle lifeCycle)
116 {
117 _thread._lifeCycles.remove(lifeCycle);
118 if (_thread._lifeCycles.size()==0)
119 _thread.unhook();
120 }
121
122
123 public static synchronized boolean isRegistered(LifeCycle lifeCycle)
124 {
125 return _thread._lifeCycles.contains(lifeCycle);
126 }
127
128
129 @Override
130 public void run()
131 {
132 for (LifeCycle lifeCycle : _thread._lifeCycles)
133 {
134 try
135 {
136 if (lifeCycle.isStarted())
137 {
138 lifeCycle.stop();
139 LOG.debug("Stopped {}",lifeCycle);
140 }
141
142 if (lifeCycle instanceof Destroyable)
143 {
144 ((Destroyable)lifeCycle).destroy();
145 LOG.debug("Destroyed {}",lifeCycle);
146 }
147 }
148 catch (Exception ex)
149 {
150 LOG.debug(ex);
151 }
152 }
153 }
154 }