Tomcat 生命周期原理
Tomcat 生命周期原理
# Tomcat 生命周期原理
由前面的内容我们知道了,Tomcat
的几个重要的组件Service
、Connector
、Engine
、Host
,那么现在就出现了一个问题,
这些组件的生命周期在Tomcat
中是如何被管理的,我们知道一般的生命周期包含:init
-初始化、start
-开始、stop
-结束、destroy
-销毁,
下面我们就开始聊一聊Tomcat
的生命周期管理。下面我们就几个重要的类进行详细说明。
# 生命周期接口类Lifecycle
首先来看一个主要的类Lifecycle
,那么这个类的作用是什么呢?其实就是定义了组件由生到死的过程。统一定义各个组件的生命周期,
当你打开这个类的时候,你就能很清晰的看到下面这张图 --->
start()
-----------------------------
| |
| init() |
NEW -»-- INITIALIZING |
| | | | ------------------«-----------------------
| | |auto | | |
| | \|/ start() \|/ \|/ auto auto stop() |
| | INITIALIZED --»-- STARTING_PREP --»- STARTING --»- STARTED --»--- |
| | | | |
| |destroy()| | |
| --»-----«-- ------------------------«-------------------------------- ^
| | | |
| | \|/ auto auto start() |
| | STOPPING_PREP ----»---- STOPPING ------»----- STOPPED -----»-----
| \|/ ^ | ^
| | stop() | | |
| | -------------------------- | |
| | | | |
| | | destroy() destroy() | |
| | FAILED ----»------ DESTROYING ---«----------------- |
| | ^ | |
| | destroy() | |auto |
| --------»----------------- \|/ |
| DESTROYED |
| |
| stop() |
----»-----------------------------»------------------------------
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
分析:由上面这张图我们能够清晰知道,组件的每一个状态的流转,其中包含了重要的生命周期函数
init()
-初始化、start()
-开始、stop()
-结束、destroy()
-销毁,以及执行每一个生命周期函数时状态的改变。
我们将上面这张图进行整理,得到下面这张更加清晰图:
由上图我们可以更加清晰的知道整个状态的流转以及每一个生命周期函数的调用过程,每一个状态有可能到
FAILED
状态,若是失败的状态,要不停止,要么直接销毁。
# 详细说明
下面我们将该类的属性及方法提出来进行一一说明
public interface Lifecycle {
//生命周期事件字符串
public static final String BEFORE_INIT_EVENT = "before_init";
public static final String AFTER_INIT_EVENT = "after_init";
public static final String START_EVENT = "start";
public static final String BEFORE_START_EVENT = "before_start";
public static final String AFTER_START_EVENT = "after_start";
public static final String STOP_EVENT = "stop";
public static final String BEFORE_STOP_EVENT = "before_stop";
public static final String AFTER_STOP_EVENT = "after_stop";
public static final String AFTER_DESTROY_EVENT = "after_destroy";
public static final String BEFORE_DESTROY_EVENT = "before_destroy";
//周期性事件:后台线程定时执行一些任务
public static final String PERIODIC_EVENT = "periodic";
//配置事件类型,只需要俩种类型 开始 结束
public static final String CONFIGURE_START_EVENT = "configure_start";
public static final String CONFIGURE_STOP_EVENT = "configure_stop";
//监听器支持方法
public void addLifecycleListener(LifecycleListener listener);
public LifecycleListener[] findLifecycleListeners();
public void removeLifecycleListener(LifecycleListener listener);
// 生命周期支持函数
public void init() throws LifecycleException;
public void start() throws LifecycleException;
public void stop() throws LifecycleException;
public void destroy() throws LifecycleException;
// 组件状态支持方法
public LifecycleState getState();
public String getStateName();
//这个是一个标志接口 比如Serializable
public interface SingleUse {
}
}
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
由以上的接口我们有看到了俩个类
LifecycleListener
和LifecycleState
,接下来我们看看这来个类的情况
# 生命周期监听接口类LifecycleListener
该类是生命周期的监听类,根据不同到事件状态来进行不同行为。
public interface LifecycleListener {
public void lifecycleEvent(LifecycleEvent event);
}
2
3
可以看打很简单的定义了一个接口,来接收生命周期事件
# 生命周期事件类LifecycleEvent
public final class LifecycleEvent extends EventObject {
private static final long serialVersionUID = 1L;
public LifecycleEvent(Lifecycle lifecycle, String type, Object data) {
// 向上转型,可接受一切实现了生命周期的组件
super(lifecycle);
this.type = type;
this.data = data;
}
// 携带额外的数据,传递给监听器数据
private final Object data;
// 事件类型
private final String type;
public Object getData() {
return data;
}
public Lifecycle getLifecycle() {
return (Lifecycle) getSource();
}
public String getType() {
return this.type;
}
}
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
# 事件对象类EventObject
由于Tomcat
的监听器可以监听任何一个组件,所有需要知道事件源是那个,因此该类就是定义确定一个事件源。
public class EventObject implements java.io.Serializable {
private static final long serialVersionUID = 5516075349620653480L;
// 事件源
protected transient Object source;
public EventObject(Object source) {
if (source == null)
throw new IllegalArgumentException("null source");
this.source = source;
}
public Object getSource() {
return source;
}
public String toString() {
return getClass().getName() + "[source=" + source + "]";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 生命周期状态枚举类LifecycleState
该类定义了事件所有的状态,就如前面画的那张图。
public enum LifecycleState {
NEW(false, null),
INITIALIZING(false, Lifecycle.BEFORE_INIT_EVENT),
INITIALIZED(false, Lifecycle.AFTER_INIT_EVENT),
STARTING_PREP(false, Lifecycle.BEFORE_START_EVENT),
// 只有这三个可用
STARTING(true, Lifecycle.START_EVENT),
STARTED(true, Lifecycle.AFTER_START_EVENT),
STOPPING_PREP(true, Lifecycle.BEFORE_STOP_EVENT),
STOPPING(false, Lifecycle.STOP_EVENT),
STOPPED(false, Lifecycle.AFTER_STOP_EVENT),
DESTROYING(false, Lifecycle.BEFORE_DESTROY_EVENT),
DESTROYED(false, Lifecycle.AFTER_DESTROY_EVENT),
FAILED(false, null);
// 组件是否可用
private final boolean available;
//事件字符串
private final String lifecycleEvent;
private LifecycleState(boolean available, String lifecycleEvent) {
this.available = available;
this.lifecycleEvent = lifecycleEvent;
}
public boolean isAvailable() {
return available;
}
public String getLifecycleEvent() {
return lifecycleEvent;
}
}
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
# Tomcat容器生命周期管理
容器是一个组件,继承自Lifecycle
接口,可以说:组件不一定是容器,容器一定时组件,容器具有自己的生命周期
事件、监听器,容器之间可以有父子关系,容器执行后台周期性的方法,,也定义了周期执行的时间。
# 类Container
见名知意,该类是一个容器类,前面我们说到的Engine
、Host
、Context
全部都是容器,引擎用来装主机,主机用来装web
应用程序。它继承了Lifecycle
说明
容器也具有自己的生命周期。 并且容器在Tomcat
中是具有等级的
public interface Container extends Lifecycle {
//操作容器事件
public static final String ADD_CHILD_EVENT = "addChild";
public static final String ADD_VALVE_EVENT = "addValve";
public static final String REMOVE_CHILD_EVENT = "removeChild";
public static final String REMOVE_VALVE_EVENT = "removeValve";
//日志管理
public Log getLogger();
public String getLogName();
//JMX相关 -不重要
//注册需要对象名
public ObjectName getObjectName();
//JMX作用域
public String getDomain();
public String getMBeanKeyProperties();
//流水线
public Pipeline getPipeline();
// tomcat集群
public Cluster getCluster();
public void setCluster(Cluster cluster);
//周期性执行事件--》Lifecycle#PERIODIC_EVENT
public int getBackgroundProcessorDelay();
public void setBackgroundProcessorDelay(int delay);
//容器名称
public String getName();
public void setName(String name);
//容器具有父子关系,操作父容器
public Container getParent();
public void setParent(Container container);
//父容器的类加载器
public ClassLoader getParentClassLoader();
public void setParentClassLoader(ClassLoader parent);
public Realm getRealm();
public void setRealm(Realm realm);
//周期性事件执行方法载体
public void backgroundProcess();
//子容器操作
public void addChild(Container child);
public void addContainerListener(ContainerListener listener);
//监听容器属性
public void addPropertyChangeListener(PropertyChangeListener listener);
//操作容器方法
public Container findChild(String name);
public Container[] findChildren();
public ContainerListener[] findContainerListeners();
public void removeChild(Container child);
public void removeContainerListener(ContainerListener listener);
public void removePropertyChangeListener(PropertyChangeListener listener);
public void fireContainerEvent(String type, Object data);
//日志操作
public void logAccess(Request request, Response response, long time,
boolean useDefault);
public AccessLog getAccessLog();
//容器线程操作
public int getStartStopThreads();
public void setStartStopThreads(int startStopThreads);
public File getCatalinaBase();
public File getCatalinaHome();
}
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
# Tomcat生命周期模板实现
# 类LifecycleBase
该类实现了Lifecycle
生命周期接口,定义了组件的生命周期状态、监听器操作函数、生命周期转换实现、回调监听器实现.
特别注意init()
函数,它是严格按照开篇的那张图进行流转的。
public abstract class LifecycleBase implements Lifecycle {
private static final Log log = LogFactory.getLog(LifecycleBase.class);
private static final StringManager sm = StringManager.getManager(LifecycleBase.class);
// 生命周期监听器
private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>();
// 当前组件状态
private volatile LifecycleState state = LifecycleState.NEW;
// 失败时是否抛出异常
private boolean throwOnFailure = true;
public boolean getThrowOnFailure() {
return throwOnFailure;
}
public void setThrowOnFailure(boolean throwOnFailure) {
this.throwOnFailure = throwOnFailure;
}
// 监听器操作
@Override
public void addLifecycleListener(LifecycleListener listener) {
lifecycleListeners.add(listener);
}
@Override
public LifecycleListener[] findLifecycleListeners() {
return lifecycleListeners.toArray(new LifecycleListener[0]);
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
lifecycleListeners.remove(listener);
}
// 回调监听器
protected void fireLifecycleEvent(String type, Object data) {
LifecycleEvent event = new LifecycleEvent(this, type, data);
for (LifecycleListener listener : lifecycleListeners) {
listener.lifecycleEvent(event);
}
}
@Override
public final synchronized void init() throws LifecycleException {
// 若当前状态不是NEW之前错误,因为只有NEW的时候才能调用init()函数,详见开篇的图
if (!state.equals(LifecycleState.NEW)) {
invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
}
try {
// 设置当前状态为INITIALIZING
setStateInternal(LifecycleState.INITIALIZING, null, false);
//模版方法 由子类去实现
initInternal();
// 状态指向INITIALIZED
setStateInternal(LifecycleState.INITIALIZED, null, false);
} catch (Throwable t) {
handleSubClassException(t, "lifecycleBase.initFail", toString());
}
}
protected abstract void initInternal() throws LifecycleException;
//开篇图的具体实现
@Override
public final synchronized void start() throws LifecycleException {
if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||
LifecycleState.STARTED.equals(state)) {
if (log.isDebugEnabled()) {
Exception e = new LifecycleException();
log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e);
} else if (log.isInfoEnabled()) {
log.info(sm.getString("lifecycleBase.alreadyStarted", toString()));
}
return;
}
if (state.equals(LifecycleState.NEW)) {
init();
} else if (state.equals(LifecycleState.FAILED)) {
stop();
} else if (!state.equals(LifecycleState.INITIALIZED) &&
!state.equals(LifecycleState.STOPPED)) {
invalidTransition(Lifecycle.BEFORE_START_EVENT);
}
try {
setStateInternal(LifecycleState.STARTING_PREP, null, false);
// 模版方法
startInternal();
if (state.equals(LifecycleState.FAILED)) {
stop();
} else if (!state.equals(LifecycleState.STARTING)) {
invalidTransition(Lifecycle.AFTER_START_EVENT);
} else {
setStateInternal(LifecycleState.STARTED, null, false);
}
} catch (Throwable t) {
handleSubClassException(t, "lifecycleBase.startFail", toString());
}
}
protected abstract void startInternal() throws LifecycleException;
/**
* {@inheritDoc} 停止函数
*/
@Override
public final synchronized void stop() throws LifecycleException {
if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) ||
LifecycleState.STOPPED.equals(state)) {
if (log.isDebugEnabled()) {
Exception e = new LifecycleException();
log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e);
} else if (log.isInfoEnabled()) {
log.info(sm.getString("lifecycleBase.alreadyStopped", toString()));
}
return;
}
//组件处于新建状态,什么都没有,不需要出发监听器
if (state.equals(LifecycleState.NEW)) {
state = LifecycleState.STOPPED;
return;
}
// 检测状态
if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED)) {
invalidTransition(Lifecycle.BEFORE_STOP_EVENT);
}
try {
if (state.equals(LifecycleState.FAILED)) {
fireLifecycleEvent(BEFORE_STOP_EVENT, null);
} else {
setStateInternal(LifecycleState.STOPPING_PREP, null, false);
}
// 子类实现
stopInternal();
if (!state.equals(LifecycleState.STOPPING) && !state.equals(LifecycleState.FAILED)) {
invalidTransition(Lifecycle.AFTER_STOP_EVENT);
}
setStateInternal(LifecycleState.STOPPED, null, false);
} catch (Throwable t) {
handleSubClassException(t, "lifecycleBase.stopFail", toString());
} finally {
// SingleUse 标识接口的用法
if (this instanceof Lifecycle.SingleUse) {
// 组件只使用一次,直接销毁
setStateInternal(LifecycleState.STOPPED, null, false);
destroy();
}
}
}
protected abstract void stopInternal() throws LifecycleException;
// 销毁方法
@Override
public final synchronized void destroy() throws LifecycleException {
if (LifecycleState.FAILED.equals(state)) {
try {
stop();
} catch (LifecycleException e) {
log.error(sm.getString("lifecycleBase.destroyStopFail", toString()), e);
}
}
if (LifecycleState.DESTROYING.equals(state) || LifecycleState.DESTROYED.equals(state)) {
if (log.isDebugEnabled()) {
Exception e = new LifecycleException();
log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e);
} else if (log.isInfoEnabled() && !(this instanceof Lifecycle.SingleUse)) {
log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString()));
}
return;
}
if (!state.equals(LifecycleState.STOPPED) && !state.equals(LifecycleState.FAILED) &&
!state.equals(LifecycleState.NEW) && !state.equals(LifecycleState.INITIALIZED)) {
invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT);
}
try {
setStateInternal(LifecycleState.DESTROYING, null, false);
destroyInternal();
setStateInternal(LifecycleState.DESTROYED, null, false);
} catch (Throwable t) {
handleSubClassException(t, "lifecycleBase.destroyFail", toString());
}
}
// 子类实现
protected abstract void destroyInternal() throws LifecycleException;
@Override
public LifecycleState getState() {
return state;
}
@Override
public String getStateName() {
return getState().toString();
}
protected synchronized void setState(LifecycleState state) throws LifecycleException {
setStateInternal(state, null, true);
}
protected synchronized void setState(LifecycleState state, Object data)
throws LifecycleException {
setStateInternal(state, data, true);
}
// 设置状态 同时触发监听器(监听器回调)
private synchronized void setStateInternal(LifecycleState state, Object data, boolean check)
throws LifecycleException {
if (log.isDebugEnabled()) {
log.debug(sm.getString("lifecycleBase.setState", this, state));
}
if (check)
if (state == null) {
invalidTransition("null");
return;
}
if (!(state == LifecycleState.FAILED ||
(this.state == LifecycleState.STARTING_PREP &&
state == LifecycleState.STARTING) ||
(this.state == LifecycleState.STOPPING_PREP &&
state == LifecycleState.STOPPING) ||
(this.state == LifecycleState.FAILED &&
state == LifecycleState.STOPPING))) {
invalidTransition(state.name());
}
}
this.state = state;
String lifecycleEvent = state.getLifecycleEvent();
if (lifecycleEvent != null) {
fireLifecycleEvent(lifecycleEvent, data);
}
}
private void invalidTransition(String type) throws LifecycleException {
String msg = sm.getString("lifecycleBase.invalidTransition", type, toString(), state);
throw new LifecycleException(msg);
}
private void handleSubClassException(Throwable t, String key, Object... args) throws LifecycleException {
setStateInternal(LifecycleState.FAILED, null, false);
ExceptionUtils.handleThrowable(t);
String msg = sm.getString(key, args);
if (getThrowOnFailure()) {
if (!(t instanceof LifecycleException)) {
t = new LifecycleException(msg, t);
}
throw (LifecycleException) t;
} else {
log.error(msg, t);
}
}
}
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# 类LifecycleMBeanBase
该模板类,实现了Tomcat
组件注册到JMX
中和从JMX
中接触的函数,初始化时注册,销毁是接触注册。
public abstract class LifecycleMBeanBase extends LifecycleBase
implements JmxEnabled {
private static final Log log = LogFactory.getLog(LifecycleMBeanBase.class);
private static final StringManager sm =
StringManager.getManager("org.apache.catalina.util");
/* Cache components of the MBean registration. */
private String domain = null;
private ObjectName oname = null;
protected MBeanServer mserver = null;
//初始化时进注册到JMX
@Override
protected void initInternal() throws LifecycleException {
if (oname == null) {
mserver = Registry.getRegistry(null, null).getMBeanServer();
oname = register(this, getObjectNameKeyProperties());
}
}
// 销毁是 解注册
@Override
protected void destroyInternal() throws LifecycleException {
unregister(oname);
}
@Override
public final void setDomain(String domain) {
this.domain = domain;
}
@Override
public final String getDomain() {
if (domain == null) {
domain = getDomainInternal();
}
if (domain == null) {
domain = Globals.DEFAULT_MBEAN_DOMAIN;
}
return domain;
}
protected abstract String getDomainInternal();
@Override
public final ObjectName getObjectName() {
return oname;
}
protected abstract String getObjectNameKeyProperties();
protected final ObjectName register(Object obj,
String objectNameKeyProperties) {
StringBuilder name = new StringBuilder(getDomain());
name.append(':');
name.append(objectNameKeyProperties);
ObjectName on = null;
try {
on = new ObjectName(name.toString());
Registry.getRegistry(null, null).registerComponent(obj, on, null);
} catch (Exception e) {
log.warn(sm.getString("lifecycleMBeanBase.registerFail", obj, name), e);
}
return on;
}
protected final void unregister(ObjectName on) {
if (on == null) {
return;
}
if (mserver == null) {
log.warn(sm.getString("lifecycleMBeanBase.unregisterNoServer", on));
return;
}
try {
mserver.unregisterMBean(on);
} catch (MBeanRegistrationException e) {
log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e);
} catch (InstanceNotFoundException e) {
log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", on), e);
}
}
@Override
public final void postDeregister() {
// NOOP
}
@Override
public final void postRegister(Boolean registrationDone) {
// NOOP
}
@Override
public final void preDeregister() throws Exception {
// NOOP
}
@Override
public final ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
this.mserver = server;
this.oname = name;
this.domain = name.getDomain().intern();
return oname;
}
}
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# 小知识
MBean
是什么?可以理解为它是一个服务,将你得组件注册到MBean
上,有MBean
对外提供功能。其实就是包装了一层。
# Tomcat
容器模板实现原理
# 类ContainerBase
该类实现了Container
接口,提供核心方法的实现。
public abstract class ContainerBase extends LifecycleMBeanBase implements Container {
private static final Log log = LogFactory.getLog(ContainerBase.class);
protected class PrivilegedAddChild implements PrivilegedAction<Void> {
private final Container child;
PrivilegedAddChild(Container child) {
this.child = child;
}
@Override
public Void run() {
addChildInternal(child);
return null;
}
}
//子容器名 子容器 容器映射
protected final HashMap<String, Container> children = new HashMap<>();
//执行后台周期性任务的周期时间
protected int backgroundProcessorDelay = -1;
// 不能用读写锁 读写锁的弊端,写锁可以降级,写锁互斥,读锁共享
protected final List<ContainerListener> listeners = new CopyOnWriteArrayList<>();
protected Log logger = null;
protected String logName = null;
// 集群 读写锁
protected Cluster cluster = null;
private final ReadWriteLock clusterLock = new ReentrantReadWriteLock();
protected String name = null;
protected Container parent = null;
protected ClassLoader parentClassLoader = null;
protected final Pipeline pipeline = new StandardPipeline(this);
private volatile Realm realm = null;
private final ReadWriteLock realmLock = new ReentrantReadWriteLock();
protected static final StringManager sm = StringManager.getManager(ContainerBase.class);
// 添加子容器的时候就进行启动
protected boolean startChildren = true;
protected final PropertyChangeSupport support =
new PropertyChangeSupport(this);
private Thread thread = null;
// 后台线程完成 信号
private volatile boolean threadDone = false;
protected volatile AccessLog accessLog = null;
private volatile boolean accessLogScanComplete = false;
//做多线程的操作
private int startStopThreads = 1;
protected ThreadPoolExecutor startStopExecutor;
//添加子容器 IS_SECURITY_ENABLED java的安全管理器
@Override
public void addChild(Container child) {
if (Globals.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> dp =
new PrivilegedAddChild(child);
AccessController.doPrivileged(dp);
} else {
addChildInternal(child);
}
}
private void addChildInternal(Container child) {
if (log.isDebugEnabled()) {
log.debug("Add child " + child + " " + this);
}
//子容器 唯一
synchronized(children) {
if (children.get(child.getName()) != null) {
throw new IllegalArgumentException(
sm.getString("containerBase.child.notUnique", child.getName()));
}
child.setParent(this); // May throw IAE
children.put(child.getName(), child);
}
try {
//根据标识符做相应的启动操作
if ((getState().isAvailable() ||
LifecycleState.STARTING_PREP.equals(getState())) &&
startChildren) {
child.start();
}
} catch (LifecycleException e) {
log.error("ContainerBase.addChild: start: ", e);
throw new IllegalStateException(sm.getString("containerBase.child.start"), e);
} finally {
// 触发容器添加事件
fireContainerEvent(ADD_CHILD_EVENT, child);
}
}
@Override
public Container findChild(String name) {
if (name == null) {
return null;
}
synchronized (children) {
return children.get(name);
}
}
@Override
public Container[] findChildren() {
synchronized (children) {
Container results[] = new Container[children.size()];
return children.values().toArray(results);
}
}
@Override
public ContainerListener[] findContainerListeners() {
ContainerListener[] results =
new ContainerListener[0];
return listeners.toArray(results);
}
@Override
public void removeChild(Container child) {
if (child == null) {
return;
}
try {
if (child.getState().isAvailable()) {
child.stop();
}
} catch (LifecycleException e) {
log.error(sm.getString("containerBase.child.stop"), e);
}
try {
if (!LifecycleState.DESTROYING.equals(child.getState())) {
child.destroy();
}
} catch (LifecycleException e) {
log.error(sm.getString("containerBase.child.destroy"), e);
}
synchronized(children) {
if (children.get(child.getName()) == null) {
return;
}
children.remove(child.getName());
}
fireContainerEvent(REMOVE_CHILD_EVENT, child);
}
//模板方法 初始化一个线程池
@Override
protected void initInternal() throws LifecycleException {
BlockingQueue<Runnable> startStopQueue = new LinkedBlockingQueue<>();
startStopExecutor = new ThreadPoolExecutor(
getStartStopThreadsInternal(),
getStartStopThreadsInternal(), 10, TimeUnit.SECONDS,
startStopQueue,
new StartStopThreadFactory(getName() + "-startStop-"));
startStopExecutor.allowCoreThreadTimeOut(true);
super.initInternal();
}
@Override
protected synchronized void startInternal() throws LifecycleException {
logger = null;
getLogger();
Cluster cluster = getClusterInternal();
if (cluster instanceof Lifecycle) {
((Lifecycle) cluster).start();
}
Realm realm = getRealmInternal();
if (realm instanceof Lifecycle) {
((Lifecycle) realm).start();
}
// Start our child containers, if any
// 启动子容器
Container children[] = findChildren();
List<Future<Void>> results = new ArrayList<>();
for (Container child : children) {
results.add(startStopExecutor.submit(new StartChild(child)));
}
MultiThrowable multiThrowable = null;
//等待子容器执行完成
for (Future<Void> result : results) {
try {
result.get();
} catch (Throwable e) {
log.error(sm.getString("containerBase.threadedStartFailed"), e);
if (multiThrowable == null) {
multiThrowable = new MultiThrowable();
}
multiThrowable.add(e);
}
}
if (multiThrowable != null) {
throw new LifecycleException(sm.getString("containerBase.threadedStartFailed"),
multiThrowable.getThrowable());
}
// 启动pipeline
if (pipeline instanceof Lifecycle) {
((Lifecycle) pipeline).start();
}
// 设置组件状态
setState(LifecycleState.STARTING);
// 启动线程
threadStart();
}
@Override
protected synchronized void stopInternal() throws LifecycleException {
// 停止状态
threadStop();
// 设置状态
setState(LifecycleState.STOPPING);
if (pipeline instanceof Lifecycle &&
((Lifecycle) pipeline).getState().isAvailable()) {
((Lifecycle) pipeline).stop();
}
Container children[] = findChildren();
List<Future<Void>> results = new ArrayList<>();
for (Container child : children) {
results.add(startStopExecutor.submit(new StopChild(child)));
}
boolean fail = false;
for (Future<Void> result : results) {
try {
result.get();
} catch (Exception e) {
log.error(sm.getString("containerBase.threadedStopFailed"), e);
fail = true;
}
}
if (fail) {
throw new LifecycleException(
sm.getString("containerBase.threadedStopFailed"));
}
// Stop our subordinate components, if any
Realm realm = getRealmInternal();
if (realm instanceof Lifecycle) {
((Lifecycle) realm).stop();
}
Cluster cluster = getClusterInternal();
if (cluster instanceof Lifecycle) {
((Lifecycle) cluster).stop();
}
}
// 销毁
@Override
protected void destroyInternal() throws LifecycleException {
Realm realm = getRealmInternal();
if (realm instanceof Lifecycle) {
((Lifecycle) realm).destroy();
}
Cluster cluster = getClusterInternal();
if (cluster instanceof Lifecycle) {
((Lifecycle) cluster).destroy();
}
if (pipeline instanceof Lifecycle) {
((Lifecycle) pipeline).destroy();
}
// Remove children now this container is being destroyed
for (Container child : findChildren()) {
removeChild(child);
}
// Required if the child is destroyed directly.
if (parent != null) {
parent.removeChild(this);
}
// If init fails, this may be null
if (startStopExecutor != null) {
startStopExecutor.shutdownNow();
}
super.destroyInternal();
}
@Override
public void logAccess(Request request, Response response, long time,
boolean useDefault) {
boolean logged = false;
if (getAccessLog() != null) {
getAccessLog().log(request, response, time);
logged = true;
}
if (getParent() != null) {
// No need to use default logger once request/response has been logged
// once
getParent().logAccess(request, response, time, (useDefault && !logged));
}
}
@Override
public AccessLog getAccessLog() {
if (accessLogScanComplete) {
return accessLog;
}
AccessLogAdapter adapter = null;
Valve valves[] = getPipeline().getValves();
for (Valve valve : valves) {
if (valve instanceof AccessLog) {
if (adapter == null) {
adapter = new AccessLogAdapter((AccessLog) valve);
} else {
adapter.add((AccessLog) valve);
}
}
}
if (adapter != null) {
accessLog = adapter;
}
accessLogScanComplete = true;
return accessLog;
}
//添加 Valve
public synchronized void addValve(Valve valve) {
pipeline.addValve(valve);
}
// 后台执行任务
@Override
public void backgroundProcess() {
if (!getState().isAvailable()) {
return;
}
Cluster cluster = getClusterInternal();
if (cluster != null) {
try {
cluster.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString("containerBase.backgroundProcess.cluster",
cluster), e);
}
}
Realm realm = getRealmInternal();
if (realm != null) {
try {
realm.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e);
}
}
Valve current = pipeline.getFirst();
while (current != null) {
try {
current.backgroundProcess();
} catch (Exception e) {
log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e);
}
current = current.getNext();
}
// 添加完各种以后 触发周期性事件
fireLifecycleEvent(Lifecycle.PERIODIC_EVENT, null);
}
@Override
public File getCatalinaBase() {
if (parent == null) {
return null;
}
return parent.getCatalinaBase();
}
@Override
public File getCatalinaHome() {
if (parent == null) {
return null;
}
return parent.getCatalinaHome();
}
// 遍历容器,触发事件
@Override
public void fireContainerEvent(String type, Object data) {
if (listeners.size() < 1) {
return;
}
ContainerEvent event = new ContainerEvent(this, type, data);
for (ContainerListener listener : listeners) {
listener.containerEvent(event);
}
}
public ObjectName[] getChildren() {
List<ObjectName> names = new ArrayList<>(children.size());
for (Container next : children.values()) {
if (next instanceof ContainerBase) {
names.add(((ContainerBase)next).getObjectName());
}
}
return names.toArray(new ObjectName[0]);
}
protected void threadStart() {
if (thread != null) {
return;
}
// 重点,如果小于=0 不会启动后台执行线程
if (backgroundProcessorDelay <= 0) {
return;
}
threadDone = false;
String threadName = "ContainerBackgroundProcessor[" + toString() + "]";
thread = new Thread(new ContainerBackgroundProcessor(), threadName);
thread.setDaemon(true);
thread.start();
}
/**
* Stop the background thread that is periodically checking for
* session timeouts.
*/
protected void threadStop() {
if (thread == null) {
return;
}
threadDone = true;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
// Ignore
}
thread = null;
}
//后天执行线程 执行器
protected class ContainerBackgroundProcessor implements Runnable {
@Override
public void run() {
Throwable t = null;
String unexpectedDeathMessage = sm.getString(
"containerBase.backgroundProcess.unexpectedThreadDeath",
Thread.currentThread().getName());
try {
while (!threadDone) {
try {
Thread.sleep(backgroundProcessorDelay * 1000L);
} catch (InterruptedException e) {
// Ignore
}
if (!threadDone) {
processChildren(ContainerBase.this);
}
}
} catch (RuntimeException|Error e) {
t = e;
throw e;
} finally {
if (!threadDone) {
log.error(unexpectedDeathMessage, t);
}
}
}
protected void processChildren(Container container) {
ClassLoader originalClassLoader = null;
try {
if (container instanceof Context) {
Loader loader = ((Context) container).getLoader();
if (loader == null) {
return;
}
originalClassLoader = ((Context) container).bind(false, null);
}
// 调用当前容器的后天执行方法
container.backgroundProcess();
Container[] children = container.findChildren();
for (Container child : children) {
// 核心,若子容器有自己的后台执行线程,这里不调用
if (child.getBackgroundProcessorDelay() <= 0) {
processChildren(child);
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("containerBase.backgroundProcess.error"), t);
} finally {
// 还原上下文类加载器
if (container instanceof Context) {
((Context) container).unbind(false, originalClassLoader);
}
}
}
}
private static class StartChild implements Callable<Void> {
private Container child;
public StartChild(Container child) {
this.child = child;
}
@Override
public Void call() throws LifecycleException {
child.start();
return null;
}
}
private static class StopChild implements Callable<Void> {
private Container child;
public StopChild(Container child) {
this.child = child;
}
@Override
public Void call() throws LifecycleException {
if (child.getState().isAvailable()) {
child.stop();
}
return null;
}
}
private static class StartStopThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
public StartStopThreadFactory(String namePrefix) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement());
thread.setDaemon(true);
return thread;
}
}
}
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# 小结
以上就是Tomcat
的生命周期,涉及到的东西还是挺多的,关键的类的设计始终贯穿着其定义的流程。