JavaWeb Tomcat
Tomcat里面有各种各样的组件,每个组件各司其职,组件之间又相互协作共同完成web服务器这样的工程。在这些组件之上,Lifecycle(生命周期机制)至关重要!在学习各个组件之前,需要看看Lifecycle是什么以及能做什么?实现原理又是怎样的?

什么是Lifecycle?

Lifecycle,其实就是一个状态机,对组件的由生到死状态的管理。
当组件在STARTING_PREPSTARTINGSTARTED时,调用start()方法没有任何效果
当组件在NEW状态时,调用start()方法会导致init()方法被立刻执行,随后start()方法被执行
当组件在STOPPING_PREPSTOPPINGSTOPPED时,调用stop()方法没有任何效果
当一个组件在NEW状态时,调用stop()方法会将组件状态变更为STOPPED,比较典型的场景就是组件启动失败,其子组件还没有启动。当一个组件停止的时候,它将尝试停止它下面的所有子组件,即使子组件还没有启动。

Lifecycle方法

Lifecycle的方法,如下所示:

  1. public interface Lifecycle {
  2. // 添加监听器
  3. public void addLifecycleListener(LifecycleListener listener);
  4. // 获取所以监听器
  5. public LifecycleListener[] findLifecycleListeners();
  6. // 移除某个监听器
  7. public void removeLifecycleListener(LifecycleListener listener);
  8. // 初始化方法
  9. public void init() throws LifecycleException;
  10. // 启动方法
  11. public void start() throws LifecycleException;
  12. // 停止方法,和start对应
  13. public void stop() throws LifecycleException;
  14. // 销毁方法,和init对应
  15. public void destroy() throws LifecycleException;
  16. // 获取生命周期状态
  17. public LifecycleState getState();
  18. // 获取字符串类型的生命周期状态
  19. public String getStateName();
  20. }

LifecycleBase

LifecycleBase是Lifecycle的基本实现。逐一来看Lifecycle的各个方法。

增加、删除和获取监听器

  1. private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>();
  2. @Override
  3. public void addLifecycleListener(LifecycleListener listener) {
  4. lifecycleListeners.add(listener);
  5. }
  6. @Override
  7. public LifecycleListener[] findLifecycleListeners() {
  8. return lifecycleListeners.toArray(new LifecycleListener[0]);
  9. }
  10. @Override
  11. public void removeLifecycleListener(LifecycleListener listener) {
  12. lifecycleListeners.remove(listener);
  13. }
  1. 生命周期监听器保存在一个线程安全的List中,CopyOnWriteArrayList。所以add和remove都是直接调用此List的相应方法。
  2. findLifecycleListeners返回的是一个数组,为了线程安全,所以这儿会生成一个新数组。

    init()方法

    1. @Override
    2. public final synchronized void init() throws LifecycleException {
    3. // 非NEW状态,不允许调用init()方法
    4. if (!state.equals(LifecycleState.NEW)) {
    5. invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
    6. }
    7. try {
    8. // 初始化逻辑之前,先将状态变更为`INITIALIZING`
    9. setStateInternal(LifecycleState.INITIALIZING, null, false);
    10. // 初始化,该方法为一个abstract方法,需要组件自行实现
    11. initInternal();
    12. // 初始化完成之后,状态变更为`INITIALIZED`
    13. setStateInternal(LifecycleState.INITIALIZED, null, false);
    14. } catch (Throwable t) {
    15. // 初始化的过程中,可能会有异常抛出,这时需要捕获异常,并将状态变更为`FAILED`
    16. ExceptionUtils.handleThrowable(t);
    17. setStateInternal(LifecycleState.FAILED, null, false);
    18. throw new LifecycleException(
    19. sm.getString("lifecycleBase.initFail",toString()), t);
    20. }
    21. }
    setStateInternal方法用于维护状态,同时在状态转换成功之后触发事件。为了状态的可见性,所以state声明为volatile类型的。
    1. private volatile LifecycleState state = LifecycleState.NEW;。
    1. private synchronized void setStateInternal(LifecycleState state,
    2. Object data, boolean check) throws LifecycleException {
    3. if (log.isDebugEnabled()) {
    4. log.debug(sm.getString("lifecycleBase.setState", this, state));
    5. }
    6. // 是否校验状态
    7. if (check) {
    8. // Must have been triggered by one of the abstract methods (assume
    9. // code in this class is correct)
    10. // null is never a valid state
    11. // state不允许为null
    12. if (state == null) {
    13. invalidTransition("null");
    14. // Unreachable code - here to stop eclipse complaining about
    15. // a possible NPE further down the method
    16. return;
    17. }
    18. // Any method can transition to failed
    19. // startInternal() permits STARTING_PREP to STARTING
    20. // stopInternal() permits STOPPING_PREP to STOPPING and FAILED to
    21. // STOPPING
    22. if (!(state == LifecycleState.FAILED ||
    23. (this.state == LifecycleState.STARTING_PREP &&
    24. state == LifecycleState.STARTING) ||
    25. (this.state == LifecycleState.STOPPING_PREP &&
    26. state == LifecycleState.STOPPING) ||
    27. (this.state == LifecycleState.FAILED &&
    28. state == LifecycleState.STOPPING))) {
    29. // No other transition permitted
    30. invalidTransition(state.name());
    31. }
    32. }
    33. // 设置状态
    34. this.state = state;
    35. // 触发事件
    36. String lifecycleEvent = state.getLifecycleEvent();
    37. if (lifecycleEvent != null) {
    38. fireLifecycleEvent(lifecycleEvent, data);
    39. }
    40. }
    看看fireLifecycleEvent方法,
    1. public void fireLifecycleEvent(String type, Object data) {
    2. // 事件监听,观察者模式的另一种方式
    3. LifecycleEvent event = new LifecycleEvent(lifecycle, type, data);
    4. LifecycleListener interested[] = listeners;// 监听器数组 关注 事件(启动或者关闭事件)
    5. // 循环通知所有生命周期时间侦听器
    6. for (int i = 0; i < interested.length; i++)
    7. // 每个监听器都有自己的逻辑
    8. interested[i].lifecycleEvent(event);
    9. }
    首先,创建一个事件对象,然通知所有的监听器发生了该事件,并做响应。

    start()方法

    1. @Override
    2. public final synchronized void start() throws LifecycleException {
    3. // `STARTING_PREP`、`STARTING`和`STARTED时,将忽略start()逻辑
    4. if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||
    5. LifecycleState.STARTED.equals(state)) {
    6. if (log.isDebugEnabled()) {
    7. Exception e = new LifecycleException();
    8. log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e);
    9. } else if (log.isInfoEnabled()) {
    10. log.info(sm.getString("lifecycleBase.alreadyStarted", toString()));
    11. }
    12. return;
    13. }
    14. // `NEW`状态时,执行init()方法
    15. if (state.equals(LifecycleState.NEW)) {
    16. init();
    17. }
    18. // `FAILED`状态时,执行stop()方法
    19. else if (state.equals(LifecycleState.FAILED)) {
    20. stop();
    21. }
    22. // 不是`INITIALIZED`和`STOPPED`时,则说明是非法的操作
    23. else if (!state.equals(LifecycleState.INITIALIZED) &&
    24. !state.equals(LifecycleState.STOPPED)) {
    25. invalidTransition(Lifecycle.BEFORE_START_EVENT);
    26. }
    27. try {
    28. // start前的状态设置
    29. setStateInternal(LifecycleState.STARTING_PREP, null, false);
    30. // start逻辑,抽象方法,由组件自行实现
    31. startInternal();
    32. // start过程中,可能因为某些原因失败,这时需要stop操作
    33. if (state.equals(LifecycleState.FAILED)) {
    34. // This is a 'controlled' failure. The component put itself into the
    35. // FAILED state so call stop() to complete the clean-up.
    36. stop();
    37. } else if (!state.equals(LifecycleState.STARTING)) {
    38. // Shouldn't be necessary but acts as a check that sub-classes are
    39. // doing what they are supposed to.
    40. invalidTransition(Lifecycle.AFTER_START_EVENT);
    41. } else {
    42. // 设置状态为STARTED
    43. setStateInternal(LifecycleState.STARTED, null, false);
    44. }
    45. } catch (Throwable t) {
    46. // This is an 'uncontrolled' failure so put the component into the
    47. // FAILED state and throw an exception.
    48. ExceptionUtils.handleThrowable(t);
    49. setStateInternal(LifecycleState.FAILED, null, false);
    50. throw new LifecycleException(sm.getString("lifecycleBase.startFail", toString()), t);
    51. }
    52. }

    stop()方法

    1. @Override
    2. public final synchronized void stop() throws LifecycleException {
    3. // `STOPPING_PREP`、`STOPPING`和STOPPED时,将忽略stop()的执行
    4. if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) ||
    5. LifecycleState.STOPPED.equals(state)) {
    6. if (log.isDebugEnabled()) {
    7. Exception e = new LifecycleException();
    8. log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e);
    9. } else if (log.isInfoEnabled()) {
    10. log.info(sm.getString("lifecycleBase.alreadyStopped", toString()));
    11. }
    12. return;
    13. }
    14. // `NEW`状态时,直接将状态变更为`STOPPED`
    15. if (state.equals(LifecycleState.NEW)) {
    16. state = LifecycleState.STOPPED;
    17. return;
    18. }
    19. // stop()的执行,必须要是`STARTED`和`FAILED`
    20. if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED)) {
    21. invalidTransition(Lifecycle.BEFORE_STOP_EVENT);
    22. }
    23. try {
    24. // `FAILED`时,直接触发BEFORE_STOP_EVENT事件
    25. if (state.equals(LifecycleState.FAILED)) {
    26. // Don't transition to STOPPING_PREP as that would briefly mark the
    27. // component as available but do ensure the BEFORE_STOP_EVENT is
    28. // fired
    29. fireLifecycleEvent(BEFORE_STOP_EVENT, null);
    30. } else {
    31. // 设置状态为STOPPING_PREP
    32. setStateInternal(LifecycleState.STOPPING_PREP, null, false);
    33. }
    34. // stop逻辑,抽象方法,组件自行实现
    35. stopInternal();
    36. // Shouldn't be necessary but acts as a check that sub-classes are
    37. // doing what they are supposed to.
    38. if (!state.equals(LifecycleState.STOPPING) && !state.equals(LifecycleState.FAILED)) {
    39. invalidTransition(Lifecycle.AFTER_STOP_EVENT);
    40. }
    41. // 设置状态为STOPPED
    42. setStateInternal(LifecycleState.STOPPED, null, false);
    43. } catch (Throwable t) {
    44. ExceptionUtils.handleThrowable(t);
    45. setStateInternal(LifecycleState.FAILED, null, false);
    46. throw new LifecycleException(sm.getString("lifecycleBase.stopFail",toString()), t);
    47. } finally {
    48. if (this instanceof Lifecycle.SingleUse) {
    49. // Complete stop process first
    50. setStateInternal(LifecycleState.STOPPED, null, false);
    51. destroy();
    52. }
    53. }
    54. }

    destroy()方法

    1. @Override
    2. public final synchronized void destroy() throws LifecycleException {
    3. // `FAILED`状态时,直接触发stop()逻辑
    4. if (LifecycleState.FAILED.equals(state)) {
    5. try {
    6. // Triggers clean-up
    7. stop();
    8. } catch (LifecycleException e) {
    9. // Just log. Still want to destroy.
    10. log.warn(sm.getString(
    11. "lifecycleBase.destroyStopFail", toString()), e);
    12. }
    13. }
    14. // `DESTROYING`和`DESTROYED`时,忽略destroy的执行
    15. if (LifecycleState.DESTROYING.equals(state) ||
    16. LifecycleState.DESTROYED.equals(state)) {
    17. if (log.isDebugEnabled()) {
    18. Exception e = new LifecycleException();
    19. log.debug(sm.getString("lifecycleBase.alreadyDestroyed", toString()), e);
    20. } else if (log.isInfoEnabled() && !(this instanceof Lifecycle.SingleUse)) {
    21. // Rather than have every component that might need to call
    22. // destroy() check for SingleUse, don't log an info message if
    23. // multiple calls are made to destroy()
    24. log.info(sm.getString("lifecycleBase.alreadyDestroyed", toString()));
    25. }
    26. return;
    27. }
    28. // 非法状态判断
    29. if (!state.equals(LifecycleState.STOPPED) &&
    30. !state.equals(LifecycleState.FAILED) &&
    31. !state.equals(LifecycleState.NEW) &&
    32. !state.equals(LifecycleState.INITIALIZED)) {
    33. invalidTransition(Lifecycle.BEFORE_DESTROY_EVENT);
    34. }
    35. try {
    36. // destroy前状态设置
    37. setStateInternal(LifecycleState.DESTROYING, null, false);
    38. // 抽象方法,组件自行实现
    39. destroyInternal();
    40. // destroy后状态设置
    41. setStateInternal(LifecycleState.DESTROYED, null, false);
    42. } catch (Throwable t) {
    43. ExceptionUtils.handleThrowable(t);
    44. setStateInternal(LifecycleState.FAILED, null, false);
    45. throw new LifecycleException(
    46. sm.getString("lifecycleBase.destroyFail",toString()), t);
    47. }
    48. }

    模板方法

    从上述源码看得出来,LifecycleBase是使用了状态机+模板模式来实现的。模板方法有下面这几个:
    1. // 初始化方法
    2. protected abstract void initInternal() throws LifecycleException;
    3. // 启动方法
    4. protected abstract void startInternal() throws LifecycleException;
    5. // 停止方法
    6. protected abstract void stopInternal() throws LifecycleException;
    7. // 销毁方法
    8. protected abstract void destroyInternal() throws LifecycleException;

    总结

    Lifecycle其实非常简单,代码也不复杂,但是剖析其实现对于理解组件的生命周期有很大的帮助,也有助于对设计模式的回顾。