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