生命周期
Catalina包括很多组件,当catalina启动的时候,也需要启动这些组件,当关闭catalina的时候同时也需要关闭这些组件。
Tomcat通过事件机制来实现这种控制,所有的组件都实现org.apache.catalina.Lifecycle接口:
package org.apache.catalina;
public interface LifecycleListener {
public void lifecycleEvent(LifecycleEvent event);
}
同时还有一个org.apache.catalina.LifecycleListener接口负责监听事件:
package org.apache.catalina;
public interface LifecycleListener {
public void lifecycleEvent(LifecycleEvent event);
}
在需要的时候组件会向它的监听类发送相应的事件:BEFORE_START_EVENT、START_EVENT、AFTER_START_EVENT、BEFORE_STOP_EVENT、STOP_EVENT、AFTER_STOP_EVENT了,org.apache.catalina.LifecycleEvent表示事件。
catalina同时提供了LifecycleSupport类简化事件处理过程:
package org.apache.catalina.util;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
public final class LifecycleSupport {
public LifecycleSupport(Lifecycle lifecycle) {
super();
this.lifecycle = lifecycle;
}
private Lifecycle lifecycle = null;
private LifecycleListener listeners[] = new LifecycleListener[0];
public void addLifecycleListener(LifecycleListener listener) {
synchronized (listeners) {
LifecycleListener results[] =
new LifecycleListener[listeners.length + 1];
for (int i = 0; i < listeners.length; i++)
results[i] = listeners[i];
results[listeners.length] = listener;
listeners = results;
}
}
public LifecycleListener[] findLifecycleListeners() {
return listeners;
}
public void fireLifecycleEvent(String type, Object data) {
LifecycleEvent event = new LifecycleEvent(lifecycle, type, data);
LifecycleListener interested[] = null;
synchronized (listeners) {
interested = (LifecycleListener[]) listeners.clone();
}
for (int i = 0; i < interested.length; i++)
interested[i].lifecycleEvent(event);
}
public void removeLifecycleListener(LifecycleListener listener) {
synchronized (listeners) {
int n = -1;
for (int i = 0; i < listeners.length; i++) {
if (listeners[i] == listener) {
n = i;
break;
}
}
if (n < 0)
return;
LifecycleListener results[] =
new LifecycleListener[listeners.length - 1];
int j = 0;
for (int i = 0; i < listeners.length; i++) {
if (i != n)
results[j++] = listeners[i];
}
listeners = results;
}
}
}