美文网首页
深入剖析Tomcat(How Tomcat works)读书笔记

深入剖析Tomcat(How Tomcat works)读书笔记

作者: 抬头挺胸才算活着 | 来源:发表于2019-12-07 20:14 被阅读0次

参考资料:
[1]. 深入剖析Tomcat(How Tomcat works)书籍代码下载地址

第六章:生命周期

  • LifeCycle接口:


  • LifeCycleEvent类

  • LifecycleListener接口

  • LifecycleSupport类
    实现了LifeCycle事件监听类相关的方法,方便LifeCycle接口的实现。



    LifecycleSupport帮助LifeCycle接口的实现的代码如下,添加和移除监听器都是间接用的LifecycleSupport的方法,然后在事件调用的地方还要放入事件触发机制。

public class SimpleContext implements Context, Pipeline, Lifecycle {
  ...
  protected LifecycleSupport lifecycle = new LifecycleSupport(this);

  public synchronized void start() throws LifecycleException {
    if (started)
      throw new LifecycleException("SimpleContext has already started");

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
    ...
  }

  // implementation of the Lifecycle interface's methods
  public void addLifecycleListener(LifecycleListener listener) {
    lifecycle.addLifecycleListener(listener);
  }

  public void removeLifecycleListener(LifecycleListener listener) {
    lifecycle.removeLifecycleListener(listener);
  }
}

上面这样做之后可以很轻松的开启和关闭整个系统,开启系统如下所示,因为tomcat中容器是包含着子容器和子配件的,父容器负责将他们开启和关闭他们。

  public synchronized void start() throws LifecycleException {
    if (started)
      throw new LifecycleException("SimpleContext has already started");

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
    started = true;
    try {
      // Start our subordinate components, if any
      if ((loader != null) && (loader instanceof Lifecycle))
        ((Lifecycle) loader).start();

      // Start our child containers, if any
      Container children[] = findChildren();
      for (int i = 0; i < children.length; i++) {
        if (children[i] instanceof Lifecycle)
          ((Lifecycle) children[i]).start();
      }

      // Start the Valves in our pipeline (including the basic),
      // if any
      if (pipeline instanceof Lifecycle)
        ((Lifecycle) pipeline).start();
      // Notify our interested LifecycleListeners
      lifecycle.fireLifecycleEvent(START_EVENT, null);
    }
    catch (Exception e) {
      e.printStackTrace();
    }

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
  }

相关文章

网友评论

      本文标题:深入剖析Tomcat(How Tomcat works)读书笔记

      本文链接:https://www.haomeiwen.com/subject/bcaugctx.html