Tomcat源码解析:3、Tomcat生命周期Lifecycle

Lifecycle

Lifecycle接口它是一个公用的接口,在Tomcat的组件中都直接或者间接的实现该类或者它的子类。所以它是一个非常重要的接口,定义了组件生命周期的一些方法,包括:init、start、stop、destroy,还有操作LifecycleListener的API,典型的观察者模式。所以它在Tomcat中起到了举足轻重的作用,熟悉它,对Tomcat的源码分析有非常大的帮助


public interface Lifecycle {


    // ----------------------------------------------------- Manifest Constants

	 // 各种Event事件说明
    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";


    // 省略其他的事件。。。



	/**
	 * 注册一个LifecycleListener观察者	 
	 */
    public void addLifecycleListener(LifecycleListener listener);

	/**
	 * 获取所有注册的LifecycleListener
	 */	
    public LifecycleListener[] findLifecycleListeners();

	/**
	 * 移除指定的LifecycleListener
	 */
    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();

	/**
	 * 获取state的文字说明
	 */
    public String getStateName();


    public interface SingleUse {
    }
}

Lifecycle主要子类

下面我们来看一下Lifecycle的主要子类:
在这里插入图片描述

LifecycleBase:它是Lifecycle的子类,它主要实现了Lifecycle的init、start、stop、destroy等一些通用的逻辑,向注册在LifecycleBase内部的LifecycleListener发出对应的事件,并且提供了initInternal、startInternal、stopInternal、destroyInternal模板方法,便于子类实现

LifecycleMBeanBase:通过重写了initInternal、destroyInternal方法,向JMX注册或者取消当前的实例。Tomcat提供了JMX进行实例管理,但是代码上强制子类调用super.initInternal

StandardServer、StandardService、Connector等容器都继承了LifecycleMBeanBase,上面截的图不太完整,所以这些容器都具有了生命周期并且可以通过JMX进行管理

下面简单介绍了LifecycleBase和LifecycleMBeanBase方法

LifecycleBase

在看LifecycleBase之前,我们首先了解下LifecycleState,定义了Lifecycle的各种状态和对应的事件

public enum LifecycleState {
	/*
	 * Lifecycle实例化完成时的状态
	 */
    NEW(false, null),
    /*
	 * Lifecycle正在初始化的状态
	 */
    INITIALIZING(false, Lifecycle.BEFORE_INIT_EVENT),
    /*
	 * Lifecycle初始化完成的状态
	 */
    INITIALIZED(false, Lifecycle.AFTER_INIT_EVENT),
    /*
	 * Lifecycle启动前的状态
	 */
    STARTING_PREP(false, Lifecycle.BEFORE_START_EVENT),
    /*
	 * Lifecycle启动中的状态
	 */
    STARTING(true, Lifecycle.START_EVENT),
    /*
	 * Lifecycle启动完成的状态
	 */
    STARTED(true, Lifecycle.AFTER_START_EVENT),
    /*
	 * Lifecycle停止前的状态
	 */
    STOPPING_PREP(true, Lifecycle.BEFORE_STOP_EVENT),
    /*
	 * Lifecycle停止中的状态
	 */
    STOPPING(false, Lifecycle.STOP_EVENT),
    /*
	 * Lifecycle停止完成的状态
	 */
    STOPPED(false, Lifecycle.AFTER_STOP_EVENT),
    /*
	 * Lifecycle销毁中的状态
	 */
    DESTROYING(false, Lifecycle.BEFORE_DESTROY_EVENT),
    /*
	 * Lifecycle销毁完成的状态
	 */
    DESTROYED(false, Lifecycle.AFTER_DESTROY_EVENT),
    /*
	 * Lifecycle启动、停止过程中出现异常
	 */
    FAILED(false, null),
    @Deprecated
    MUST_STOP(true, null),
    @Deprecated
    MUST_DESTROY(false, null);

    private final boolean available;
    private final String lifecycleEvent;

    private LifecycleState(boolean available, String lifecycleEvent) {
        this.available = available;
        this.lifecycleEvent = lifecycleEvent;
    }
    public boolean isAvailable() {
        return available;
    }

    public String getLifecycleEvent() {
        return lifecycleEvent;
    }
}
public abstract class LifecycleBase implements Lifecycle {

    private static final Log log = LogFactory.getLog(LifecycleBase.class);

    private static final StringManager sm =
        StringManager.getManager("org.apache.catalina.util");

	/**
	 * 存储LifecycleListener的容器,里面封装了一个List集合,因为存在并发操做
	 * 所以使用了CopyOnWriteArrayList
	 * List<LifecycleListener> listeners = new CopyOnWriteArrayList<>();
	 */
    private final LifecycleSupport lifecycle = new LifecycleSupport(this);

    private volatile LifecycleState state = LifecycleState.NEW;

	/*
	 * 注册一个LifecycleListener
	 */
    @Override
    public void addLifecycleListener(LifecycleListener listener) {
        lifecycle.addLifecycleListener(listener);
    }	
    
	/*
	 * 获取注册的所有LifecycleListener
	 */
    @Override
    public LifecycleListener[] findLifecycleListeners() {
        return lifecycle.findLifecycleListeners();
    }

	/*
	 * 移除指定的LifecycleListener
	 */
    @Override
    public void removeLifecycleListener(LifecycleListener listener) {
        lifecycle.removeLifecycleListener(listener);
    }
    
	/*
	 * 触发事件,通知所有的LifecycleListener
	 */
    protected void fireLifecycleEvent(String type, Object data) {
        lifecycle.fireLifecycleEvent(type, data);
    }

	/*
	 * 设置state状态,不传数据,实际调用的是setStateInternal,第三个参数为true,表示需要校验state合法规则
	 * 这里使用了synchronized,因为可能存在并发操作
	 */
	protected synchronized void setState(LifecycleState state)
            throws LifecycleException {
        setStateInternal(state, null, true);
    }

	
	/*
	 * 设置state状态,并且传数据,实际调用的是setStateInternal,第三个参数为true,表示需要校验state合法规则
	 * 这里使用了synchronized,因为可能存在并发操作
	 */
    protected synchronized void setState(LifecycleState state, Object data)
            throws LifecycleException {
        setStateInternal(state, data, true);
    }
	
	/*
	 * 真正修改state状态的方法
	 */
    private synchronized void setStateInternal(LifecycleState state,
            Object data, boolean check) throws LifecycleException {

        if (log.isDebugEnabled()) {
            log.debug(sm.getString("lifecycleBase.setState", this, state));
        }
		
		 /*
		  * 如果check为true,则需要校验state是否合法
		  */
        if (check) {
            /*
             * 如果设置的state为Null,抛出异常
             */
            if (state == null) {
                invalidTransition("null");
                return;
            }
            
            /*
             * 下面是state合法校验规则
             * 出现下面一种情况都会调用invalidTransition抛出异常
             * 1、如果当前state是LifecycleState.STARTING_PREP,那么修改的state一定要是LifecycleState.STARTING,要不抛出异常
             * 2、如果当前state是LifecycleState.STOPPING_PREP,那么修改的state一定要是 LifecycleState.STOPPING,要不抛出异常
             * 3、如果当前state是LifecycleState.FAILED,那么修改的state一定是LifecycleState.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))) {
                invalidTransition(state.name());
            }
        }
		 // 设置修改的state
        this.state = state;
        // 获取state的事件描述
        String lifecycleEvent = state.getLifecycleEvent();
        if (lifecycleEvent != null) {
        	  // 触发lifecycleEvent事件,并且通知所有注册的监听者
            fireLifecycleEvent(lifecycleEvent, data);
        }
    }

	
	/*
	 * 初始化方法
	 */
    @Override
    public final synchronized void init() throws LifecycleException {    
        /*
         * 如果当前state不是LifecycleState.NEW,则调用invalidTransition抛出异常
         */  	 
        if (!state.equals(LifecycleState.NEW)) {
            invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
        }
  
        try {
        	  /*
        	   * 调用setStateInternal修改state为LifecycleState.INITIALIZING
        	   * 并且第三个参数为false,则不需要校验state合法规则,之前setStateInternal有说过     	  
        	   */
            setStateInternal(LifecycleState.INITIALIZING, null, false);
            /*
             * 调用initInternal模板方法,这个由子类实现
             */
            initInternal();
            /*
        	   * 调用setStateInternal修改state为LifecycleState.INITIALIZED
        	   * 并且第三个参数为false,则不需要校验state合法规则,之前setStateInternal有说过     	  
        	   */
            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);
        }
    }

	/*
	 * initInternal模板方法,由子类实现
	 */
    protected abstract void initInternal() throws LifecycleException;


	/*
	 * 启动方法
	 */
    @Override
    public final synchronized void start() throws LifecycleException {
		
		 /*
		  * 如果当前state是
		  * LifecycleState.STARTING_PREP、LifecycleState.STARTING、LifecycleState.STARTED,
		  * 说明已经启动过了,那么直接抛出异常
		  */
        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;
        }
		
		 /*
		  * 如果当前state是LifecycleState.NEW,那么调用 init();
		  */
        if (state.equals(LifecycleState.NEW)) {
            init();
        /*
		  * 如果当前state是LifecycleState.FAILED,那么调用 stop();
		  */
        } else if (state.equals(LifecycleState.FAILED)) {
            stop();
        /*
		  * 如果当前state不是LifecycleState.INITIALIZED或者LifecycleState.STOPPED,则直接抛出异常
		  */
        } else if (!state.equals(LifecycleState.INITIALIZED) &&
                !state.equals(LifecycleState.STOPPED)) {
            invalidTransition(Lifecycle.BEFORE_START_EVENT);
        }

        try {
			 /*
        	  * 调用setStateInternal修改state为LifecycleState.STARTING_PREP
        	  * 并且第三个参数为false,则不需要校验state合法规则,之前setStateInternal有说过     	  
        	  */
            setStateInternal(LifecycleState.STARTING_PREP, null, false);
            /*
             * 调用startInternal模板方法
             */
            startInternal();
            /*
             * 如果调用startInternal后,state为LifecycleState.FAILED
             * 那么调用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();
            /*
             * 如果调用startInternal后,
             * state不是LifecycleState.STARTING
             * 那么调用 invalidTransition抛出异常,            
             */
            } 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);
                /*                
                 *  如果调用startInternal后,
                 *  state是LifecycleState.STARTING,
             	   *  那么调用setStateInternal(LifecycleState.STARTED, null, false);
                 */
            } 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);
        }
    }

    /*
     *startInternal模板方法
     */
    protected abstract void startInternal() throws LifecycleException;

	/*
	 * 停止方法,逻辑跟start()差不多,就不分析了
	 */
    @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;

	
	/*
	 * 销毁方法,逻辑跟start()差不多,就不分析了
	 */
    @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;

    /**
     * {@inheritDoc}
     */
    @Override
    public LifecycleState getState() {
        return state;
    }


    /**
     * {@inheritDoc}
     */
    @Override
    public String getStateName() {
        return getState().toString();
    }


    
}

整个init、start、stop、destroy方法state状态改变顺序,可以看下Lifecycle接口里有个官方注释

 *            start()
 *  -----------------------------
 *  |                           |
 *  | init()                    |
 * NEW -»-- INITIALIZING        |
 * | |           |              |     ------------------«-----------------------
 * | |           |auto          |     |                                        |
 * | |          \|/    start() \|/   \|/     auto          auto         stop() |
 * | |      INITIALIZED --»-- STARTING_PREP --»- STARTING --»- STARTED --»---  |
 * | |         |                                                            |  |
 * | |destroy()|                                                            |  |
 * | --»-----«--    ------------------------«--------------------------------  ^
 * |     |          |                                                          |
 * |     |         \|/          auto                 auto              start() |
 * |     |     STOPPING_PREP ----»---- STOPPING ------»----- STOPPED -----»-----
 * |    \|/                               ^                     |  ^
 * |     |               stop()           |                     |  |
 * |     |       --------------------------                     |  |
 * |     |       |                                              |  |
 * |     |       |    destroy()                       destroy() |  |
 * |     |    FAILED ----»------ DESTROYING ---«-----------------  |
 * |     |                        ^     |                          |
 * |     |     destroy()          |     |auto                      |
 * |     --------»-----------------    \|/                         |
 * |                                 DESTROYED                     |
 * |                                                               |
 * |                            stop()                             |
 * ----»-----------------------------»------------------------------

LifecycleMBeanBase

继承了LifecycleBase类,实现了initInternal和destroyInternal方法,提供子类统一注册JMX实例的方法,所以代码上强制子类调用super.initInternal往JMX中注册实例。

public abstract class LifecycleMBeanBase extends LifecycleBase
        implements JmxEnabled {

    private ObjectName oname = null;
    protected MBeanServer mserver = null;

    @Override
    protected void initInternal() throws LifecycleException {

        // If oname is not null then registration has already happened via
        // preRegister().
        if (oname == null) {
            mserver = Registry.getRegistry(null, null).getMBeanServer();

            oname = register(this, getObjectNameKeyProperties());
        }
    }
    @Override
    protected void destroyInternal() throws LifecycleException {
        unregister(oname);
    }
	
	/*
	 * 模板方法,子类注册到JMX的实例名称
	 */
    protected abstract String getObjectNameKeyProperties();
	
	// 省略其他的方法

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值