Lifecycle-生命周期

官方接口文档:http://tomcat.apache.org/tomcat-9.0-doc/api/org/apache/catalina/Lifecycle.html

生命周期流转图

类图

生命周期

plantUML

@startuml
interface Lifecycle{
    + String BEFORE_INIT_EVENT = "before_init"
    + String AFTER_INIT_EVENT = "after_init"
    + String START_EVENT = "start"
    + String BEFORE_START_EVENT = "before_start"
    + String AFTER_START_EVENT = "after_start"
    + String STOP_EVENT = "stop"
    + String BEFORE_STOP_EVENT = "before_stop"
    + String AFTER_STOP_EVENT = "after_stop"
    + String AFTER_DESTROY_EVENT = "after_destroy"
    + String BEFORE_DESTROY_EVENT = "before_destroy"
    + String PERIODIC_EVENT = "periodic"
    + String CONFIGURE_START_EVENT = "configure_start"
    + String CONFIGURE_STOP_EVENT = "configure_stop"
    + void addLifecycleListener(LifecycleListener listener)
    + LifecycleListener[] findLifecycleListeners()
    + void removeLifecycleListener(LifecycleListener listener)
    + void init() throws LifecycleException
    + void start() throws LifecycleException
    + void stop() throws LifecycleException
    + void destroy() throws LifecycleException
    + LifecycleState getState()
    + String getStateName()
    + interface SingleUse {}
}

interface LifecycleListener{
    + lifecycleEvent(LifecycleEvent event)
}

Lifecycle .> LifecycleListener

class LifecycleEvent{
    + LifecycleEvent(Lifecycle lifecycle, String type, Object data)
    - final Object data
    - final String type
    + Object getData()
    + Lifecycle getLifecycle()
    + String getType()
}

LifecycleListener .> LifecycleEvent
LifecycleEvent --> Lifecycle

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);
}
Lifecycle .> LifecycleState

@enduml

Lifecycle

生命周期接口:

  • 内部定义了Lifecycle.SingleUse接口:标识接口,实现该接口的实例在使用一次后就会被销毁
 @Override
    public final synchronized void stop() throws LifecycleException {

        ...
        try {
            ...
        } catch (Throwable t) {
            handleSubClassException(t, "lifecycleBase.stopFail", toString());
        } finally {
            if (this instanceof Lifecycle.SingleUse) {
                // Complete stop process first
                setStateInternal(LifecycleState.STOPPED, null, false);
                destroy();
            }
        }
    }

LifecycleBase

生命周期接口基本实现

源码阅读

    private static final Log log = LogFactory.getLog(LifecycleBase.class);
    private static final StringManager sm = StringManager.getManager(LifecycleBase.class);
    private final List<LifecycleListener> lifecycleListeners = new CopyOnWriteArrayList<>();
    private volatile LifecycleState state = LifecycleState.NEW;
    private boolean throwOnFailure = true;
    public boolean getThrowOnFailure() {
        return throwOnFailure;
    }
    public void setThrowOnFailure(boolean throwOnFailure) {
        this.throwOnFailure = throwOnFailure;
    }
   @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);
    }
   protected void fireLifecycleEvent(String type, Object data) {
        LifecycleEvent event = new LifecycleEvent(this, type, data);
        for (LifecycleListener listener : lifecycleListeners) {
            listener.lifecycleEvent(event);
        }
    }
  • log:日志打印
  • StringManager : 这个类可以看具体实现,用了单例模式,是针对每个包生成一个单例,用来管理ResourceBundle,根据各个包相关的提示信息等
  • lifecycleListeners :监听器,线程安全的list
  • state :实例的当前状态(或是说生命周期的那个阶段)
  • throwOnFailure :钩子方法的值,由子类来设置是否需要在错误的时候抛异常
  • 以及几个监听器管理相关的方法
@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) {
            handleSubClassException(t, "lifecycleBase.initFail", toString());
        }
    }
  protected abstract void initInternal() throws LifecycleException;
  • init(): 使用了模板方法模式,init给出了初始化的基本步骤

    1. final :不能被子类复写
    2. synchronized :线程安全
    3. 检查前置状态是否正确(LifecycleState.NEW),错误就会抛出异常
    4. 设置为LifecycleState.INITIALIZING,并执行监听器(before_init)
    5. 执行子类实现的初始化方法initInternal()
    6. 设置为LifecycleState.INITIALIZED,并执行监听器(after_init)
    7. 4,5,6执行过程失败,将设置为LifecycleState.FAILED, 由throwOnFailure 控制是否抛异常
  • initInternal():初始化具体的实现由子类提供

 @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)) {
                stop();
            } else if (!state.equals(LifecycleState.STARTING)) {
                invalidTransition(Lifecycle.AFTER_START_EVENT);
            } else {
                setStateInternal(LifecycleState.STARTED, null, false);
            }
        } catch (Throwable t) {
            handleSubClassException(t, "lifecycleBase.startFail", toString());
        }
    }
    protected abstract void startInternal() throws LifecycleException;
  • start(): 使用了模板方法模式
    1. final :不能被子类复写
    2. synchronized :线程安全
    3. 前置状态检查(LifecycleState.STARTING_PREP,LifecycleState.STARTING,LifecycleState.STARTED)属于前置状态错误,输出相关日志并结束调用
    4. 前置状态是LifecycleState.NEW,就先init()初始化
    5. 前置状态是LifecycleState.FAILED,就先stop()
    6. 前置状态不是LifecycleState.INITIALIZED或LifecycleState.STOPPED,会抛出异常
    7. 设置为LifecycleState.STARTING_PREP,并执行监听器(before_start)
    8. startInternal():子类实现需要把状态置为LifecycleState.STARTING,执行失败可能需要置为LifecycleState.FAILED
    9. 如果状态为LifecycleState.FAILED,会调用stop()
    10. 如果状态不为LifecycleState.STARTING,会抛异常
    11. 执行成功,设置为LifecycleState.STARTED,并执行监听器(after_start)
    12. 7,8,9,10,11执行过程失败,将设置为LifecycleState.FAILED, 由throwOnFailure 控制是否抛异常
  • startInternal():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)) {
                fireLifecycleEvent(BEFORE_STOP_EVENT, null);
            } else {
                setStateInternal(LifecycleState.STOPPING_PREP, null, false);
            }
            stopInternal();

            if (!state.equals(LifecycleState.STOPPING) && !state.equals(LifecycleState.FAILED)) {
                invalidTransition(Lifecycle.AFTER_STOP_EVENT);
            }

            setStateInternal(LifecycleState.STOPPED, null, false);
        } catch (Throwable t) {
            handleSubClassException(t, "lifecycleBase.stopFail", toString());
        } finally {
            if (this instanceof Lifecycle.SingleUse) {
                setStateInternal(LifecycleState.STOPPED, null, false);
                destroy();
            }
        }
    }

    protected abstract void stopInternal() throws LifecycleException;
  • stop(): 使用了模板方法模式

    1. final :不能被子类复写
    2. synchronized :线程安全
    3. 前置状态检查(LifecycleState.STOPPING_PREP,LifecycleState.STOPPING,LifecycleState.STOPPED)前置状态错误,输出相关日志并结束调用
    4. 前置状态为LifecycleState.NEW,直接修改状态为LifecycleState.STOPPED
    5. 前置状态不为LifecycleState.STARTED和LifecycleState.FAILED,抛出异常
    6. 前置状态为LifecycleState.FAILED,直接先执行监听器(before_stop)
    7. 前置状态为LifecycleState.STARTED,设置状态为LifecycleState.STOPPING_PREP并执行监听器(before_stop)
    8. stopInternal():需要将状态置为LifecycleState.STOPPING或LifecycleState.FAILED
    9. 如果 stopInternal()设置的状态不正确就抛异常
    10. 设置状态为LifecycleState.STOPPED,并执行监听器(after_stop)
    11. 6,7,8,9,10 可能抛异常
    12. 如果之类实现了Lifecycle.SingleUse接口,会执行destroy()
  • stopInternal():子类具体实现

 @Override
    public final synchronized void destroy() throws LifecycleException {
        if (LifecycleState.FAILED.equals(state)) {
            try {            
                stop();
            } catch (LifecycleException e) {             
                log.error(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)) {          
                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) {
            handleSubClassException(t, "lifecycleBase.destroyFail", toString());
        }
    }

    protected abstract void destroyInternal() throws LifecycleException;
  • destroy(): 模板方法模式

    1. final :不能被子类复写
    2. synchronized :线程安全
    3. 前置状态为LifecycleState.FAILED,先执行stop()
    4. 前置状态为LifecycleState.DESTROYING或LifecycleState.DESTROYED,打印日志,结束调用
    5. 前置状态不为LifecycleState.STOPPED,LifecycleState.FAILED,LifecycleState.NEW,LifecycleState.INITIALIZED,抛出异常
    6. 设置状态为LifecycleState.DESTROYING 并执行监听器(before_destory)
    7. destroyInternal()
    8. 设置状态为LifecycleState.DESTROYED 并执行监听器 (after_destory)
    9. 6,7,8 可能抛异常
  • destroyInternal():子类实现具体的销毁方法

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

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

    protected synchronized void setState(LifecycleState state) throws LifecycleException {
        setStateInternal(state, null, true);
    }

    protected synchronized void setState(LifecycleState state, Object data)
            throws LifecycleException {
        setStateInternal(state, data, true);
    }


    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) {     
            if (state == null) {
                invalidTransition("null");  
                return;
            } 
            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());
            }
        }
        this.state = state;
        String lifecycleEvent = state.getLifecycleEvent();
        if (lifecycleEvent != null) {
            fireLifecycleEvent(lifecycleEvent, data);
        }
    }

    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 {
        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);
        }
    }
  • setState(): 具体细节是setStateInternal()为子类提供的设置状态的方法,且必须检查对应的状态是否正确
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,723评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,485评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,998评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,323评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,355评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,079评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,389评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,019评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,519评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,971评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,100评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,738评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,293评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,289评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,517评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,547评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,834评论 2 345

推荐阅读更多精彩内容