美文网首页Tomcat
Tomcat启动分析(三) - Lifecycle接口

Tomcat启动分析(三) - Lifecycle接口

作者: buzzerrookie | 来源:发表于2018-09-13 19:26 被阅读2次

    Lifecycle是Tomcat中的一个重要接口,许多组件如Server、Service和Connector等都继承或实现了该接口。本文首先引入Lifecycle接口,然后介绍与Lifecycle接口相关的辅助接口,最后分析LifecycleBase抽象类。

    Lifecycle接口

    Lifecycle接口的类层次结构如下图所示。


    Lifecycle类层次结构.png

    接口方法的含义从方法名称即可明白:

    public interface Lifecycle {
        // ----------------------------------------------------- Manifest Constants
        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 Methods
        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();
        public interface SingleUse {}
    }
    

    LifecycleListener接口

    LifecycleListener接口只有一个方法,该方法响应其关注的生命周期事件。

    public interface LifecycleListener {
    
        public void lifecycleEvent(LifecycleEvent event);
    }
    

    LifecycleState枚举

    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);
        // 省略一些代码
    }
    

    LifecycleBase类

    LifecycleBase类是实现了Lifecycle接口的抽象类,提供了Lifecycle接口的基本实现。
    成员变量很简单,包括一个保存Listener的List和一个状态枚举变量:

    private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>();
    private volatile LifecycleState state = LifecycleState.NEW;
    

    成员方法:

    • addLifecycleListener、removeLifecycleListener、getState和getStateName方法都很简单,都是对这两个变-的操作,在此不再赘述;
    • init、start、stop和destroy这四个生命周期方法都是模板方法,这些方法都是只能在组件处于特定状态时才能被调用,否则会抛出异常。

    init方法

    init方法是一个final的模板方法,子类需要实现initInternal抽象方法去完成自己的初始化工作。init方法先将组件状态置为INITIALIZING,待initInternal方法成功执行完真正的初始化工作后,组件状态被置为INITIALIZED,若出错则状态被置为FAILED。

    @Override
    public final synchronized void init() throws LifecycleException {
        if (!state.equals(LifecycleState.NEW)) {
            invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
        }
    
        try {
            setStateInternal(LifecycleState.INITIALIZING, null, false);
            initInternal();
            setStateInternal(LifecycleState.INITIALIZED, null, false);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            setStateInternal(LifecycleState.FAILED, null, false);
            throw new LifecycleException(sm.getString("lifecycleBase.initFail",toString()), t);
        }
    }
    
    protected abstract void initInternal() throws LifecycleException;
    

    start方法

    start方法是一个final的模板方法,子类需要实现startInternal抽象方法去完成自己的启动工作。start方法先将组件状态置为STARTING_PREP,待startInternal方法成功执行完真正的启动工作后,组件状态被置为STARTED,若出错则状态被置为FAILED。

    • 若组件状态为STARTING_PREP或者STARTING,那么再次调用start方法不会有任何效果;
    • 若组件状态还未初始化,那么会先调用init方法初始化组件。
    @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)) {
                // This is a 'controlled' failure. The component put itself into the
                // FAILED state so call stop() to complete the clean-up.
                stop();
            } else if (!state.equals(LifecycleState.STARTING)) {
                // Shouldn't be necessary but acts as a check that sub-classes are
                // doing what they are supposed to.
                invalidTransition(Lifecycle.AFTER_START_EVENT);
            } else {
                setStateInternal(LifecycleState.STARTED, null, false);
            }
        } catch (Throwable t) {
            // This is an 'uncontrolled' failure so put the component into the
            // FAILED state and throw an exception.
            ExceptionUtils.handleThrowable(t);
            setStateInternal(LifecycleState.FAILED, null, false);
            throw new LifecycleException(sm.getString("lifecycleBase.startFail", toString()), t);
        }
    }
    
    protected abstract void startInternal() throws LifecycleException;
    

    stop方法

    stop方法是一个final的模板方法,子类需要实现stopInternal抽象方法去完成自己的停止工作。待stopInternal方法成功执行完真正的停止工作后,组件状态被置为STOPPED,若出错则状态被置为FAILED。

    @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)) {
                // Don't transition to STOPPING_PREP as that would briefly mark the
                // component as available but do ensure the BEFORE_STOP_EVENT is
                // fired
                fireLifecycleEvent(BEFORE_STOP_EVENT, null);
            } else {
                setStateInternal(LifecycleState.STOPPING_PREP, null, false);
            }
    
            stopInternal();
    
            // Shouldn't be necessary but acts as a check that sub-classes are
            // doing what they are supposed to.
            if (!state.equals(LifecycleState.STOPPING) && !state.equals(LifecycleState.FAILED)) {
                invalidTransition(Lifecycle.AFTER_STOP_EVENT);
            }
    
            setStateInternal(LifecycleState.STOPPED, null, false);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            setStateInternal(LifecycleState.FAILED, null, false);
            throw new LifecycleException(sm.getString("lifecycleBase.stopFail",toString()), t);
        } finally {
            if (this instanceof Lifecycle.SingleUse) {
                // Complete stop process first
                setStateInternal(LifecycleState.STOPPED, null, false);
                destroy();
            }
        }
    }
    
    protected abstract void stopInternal() throws LifecycleException;
    

    destroy方法

    destroy方法是一个final的模板方法,子类需要实现destroyInternal抽象方法去完成自己的销毁工作。destroy方法先将组件状态置为DESTROYING,待destroyInternal方法成功执行完真正的销毁工作后,组件状态被置为DESTROYED,若出错则状态被置为FAILED。

    @Override
    public final synchronized void destroy() throws LifecycleException {
        if (LifecycleState.FAILED.equals(state)) {
            try {
                // Triggers clean-up
                stop();
            } catch (LifecycleException e) {
                // Just log. Still want to destroy.
                log.warn(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)) {
                // Rather than have every component that might need to call
                // destroy() check for SingleUse, don't log an info message if
                // multiple calls are made to destroy()
                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) {
            ExceptionUtils.handleThrowable(t);
            setStateInternal(LifecycleState.FAILED, null, false);
            throw new LifecycleException(sm.getString("lifecycleBase.destroyFail",toString()), t);
        }
    }
    
    protected abstract void destroyInternal() throws LifecycleException;
    

    后续会重点分析各子类的initInternal和startInternal方法。

    LifecycleMBeanBase类

    LifecycleMBeanBase抽象类是LifecycleBase抽象类的子类,同时实现了JmxEnabled接口,这个接口与JMX有关,不太懂JMX,暂时略过。

    相关文章

      网友评论

        本文标题:Tomcat启动分析(三) - Lifecycle接口

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