美文网首页
Lifecycle-生命周期

Lifecycle-生命周期

作者: stayiwithime | 来源:发表于2021-03-23 14:22 被阅读0次

官方接口文档: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()为子类提供的设置状态的方法,且必须检查对应的状态是否正确

相关文章

  • Jetpack-Lifecycle

    Lifecycle介绍 相关类和接口 使用 实现原理 Lifecycle-生命周期感知组件 Lifecycle是J...

  • Lifecycle-生命周期

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

  • Lifecycle-生命周期感知型组件

    简介 Lifecycle是Google推荐的架构组件之一. 生命周期感知型组件可执行操作来响应另一个组件(如 Ac...

  • IDEA 打包spring boot 并上线运行

    运行: moven->demo->lifecycle->package 结果:target/demo-0.0.1...

  • Vue生命周期

    什么是生命周期方法?生命周期钩子=生命周期函数=生命周期事件 Vue生命周期方法分类  创建期间的生命周期方法: ...

  • Activity,Fragment,Service生命周期图

    Activity生命周期 Fragment生命周期 Service生命周期

  • 10,vue生命周期

    生命周期钩子=生命周期函数=生命周期事件 根据生命周期的不同分为三类: 创建阶段的生命周期 运行阶段的生命周期 销...

  • 微信小程序生命周期的记录

    小程序中生命周期分为3类: 应⽤的生命周期 页面的生命周期 组件的生命周期 一、生命周期 1. 应⽤的生命周期[h...

  • Lifecycle 生命周期源码解析

    目录: 什么生命周期 什么是生命周期感知型组件 Activity是如何把生命周期传给生命周期感知组件的 生命周期 ...

  • Vue生命周期

    Vue生命周期详解 一、Vue生命周期 与 作用 (生命周期钩子就是生命周期函数) (1)Vue生命周期:每个Vu...

网友评论

      本文标题:Lifecycle-生命周期

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