1. Lifecycle

Lifecycle是Tomcat的生命周期机制的体现。
Lifecycle实际上是一个状态机,下面给出状态转换图:
Lifecycle状态机转换图
这个状态图是根据实现类LifecycleBase中的方法实现的转态转换而画。

Lifecycle:

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();
}

2. LifecycleBase

LifecycleBase是Lifecycle的实现,Tomcat 里只要有生命周期的组件都会继承LifecycleBase。

监听器相关:

// 生命周期监听器都保存在线程安全的CopyOnWriteArrayList中
private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>();

@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);
}

init():

@Override
public final synchronized void init() throws LifecycleException {
	// 不是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) {
    	// 初始化过程中出现异常,变更状态为FAILED
        handleSubClassException(t, "lifecycleBase.initFail", toString());
    }
}

protected abstract void initInternal() throws LifecycleException;

start():

public final synchronized void start() throws LifecycleException {

	// 如果状态不是STARTING_PREP、STARTING、STARTED,不执行start()
    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;
    }

	// NEW状态时,执行init()
    if (state.equals(LifecycleState.NEW)) {
        init();
        // FAILED状态时,执行stop()
    } else if (state.equals(LifecycleState.FAILED)) {
        stop();
        // 不是INITIALIZED和STOPPED,非法操作
    } else if (!state.equals(LifecycleState.INITIALIZED) &&
            !state.equals(LifecycleState.STOPPED)) {
        invalidTransition(Lifecycle.BEFORE_START_EVENT);
    }

    try {
    	// start前,变更状态为STARTING_PREP
        setStateInternal(LifecycleState.STARTING_PREP, null, false);
        // 模板方法,供子类实现
        startInternal();
        // start()过程中,如果失败了,执行stop()
        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 {
        	// start后,变更状态为STARTED
            setStateInternal(LifecycleState.STARTED, null, false);
        }
    } catch (Throwable t) {
		// start过程中出现异常,变更状态为FAILED
        handleSubClassException(t, "lifecycleBase.startFail", toString());
    }
}

stop():

public final synchronized void stop() throws LifecycleException {
	// 如果状态不是STOPPING_PREP、STOPPING、STOPPED,不执行stop()
    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;
    }
	// NEW状态时,变更状态为STOPPED
    if (state.equals(LifecycleState.NEW)) {
        state = LifecycleState.STOPPED;
        return;
    }
	
	// 状态不是STARTED和FAILED,不执行stop()
    if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED)) {
        invalidTransition(Lifecycle.BEFORE_STOP_EVENT);
    }

    try {
    	// FAILED时,直接触发BEFORE_STOP_EVENT事件
        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 {
        	// 设置状态为STOPPING_PREP
            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);
        }
		// 设置状态为STOPPED
        setStateInternal(LifecycleState.STOPPED, null, false);
    } catch (Throwable t) {
        handleSubClassException(t, "lifecycleBase.stopFail", toString());
    } finally {
        if (this instanceof Lifecycle.SingleUse) {
            // Complete stop process first
            setStateInternal(LifecycleState.STOPPED, null, false);
            destroy();
        }
    }
}

destroy():

public final synchronized void destroy() throws LifecycleException {
	// FAILED状态时,执行stop()
    if (LifecycleState.FAILED.equals(state)) {
        try {
            // Triggers clean-up
            stop();
        } catch (LifecycleException e) {
            // Just log. Still want to destroy.
            log.error(sm.getString("lifecycleBase.destroyStopFail", toString()), e);
        }
    }

	// DESTROYING或DESTROYED时,不执行destroy()
    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 {
    	// destroy前,变更状态为DESTROYING
        setStateInternal(LifecycleState.DESTROYING, null, false);
        // 模板方法,供子类实现
        destroyInternal();
        // destroy后,变更状态为DESTROYED
        setStateInternal(LifecycleState.DESTROYED, null, false);
    } catch (Throwable t) {
        handleSubClassException(t, "lifecycleBase.destroyFail", toString());
    }
}

setStateInternal:

// state声明为volatile类型,保证状态可见性
private volatile LifecycleState state = LifecycleState.NEW;

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) {
        // state不允许为null
        if (state == null) {
            invalidTransition("null");
            return;
        }

        // Any method can transition to failed
        // startInternal() permits STARTING_PREP to STARTING
        // stopInternal() permits STOPPING_PREP to STOPPING and FAILED to
        // STOPPING
        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))) {
            // No other transition permitted
            invalidTransition(state.name());
        }
    }

	// 设置状态
    this.state = state;
    String lifecycleEvent = state.getLifecycleEvent();
    if (lifecycleEvent != null) {
        fireLifecycleEvent(lifecycleEvent, data);
    }
}

protected void fireLifecycleEvent(String type, Object data) {
    LifecycleEvent event = new LifecycleEvent(this, type, data);
    for (LifecycleListener listener : lifecycleListeners) {
        listener.lifecycleEvent(event);
    }
}
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 {
	// 变更状态为FAILED
    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);
    }
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐