欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Tomcat源码分析 (三)----- 生命周期机制 Lifecycle

程序员文章站 2022-07-01 16:19:06
Tomcat里面有各种各样的组件,每个组件各司其职,组件之间又相互协作共同完成web服务器这样的工程。在这些组件之上,Lifecycle(生命周期机制)至关重要!在学习各个组件之前,我们需要看看Lifecycle是什么以及能做什么?实现原理又是怎样的? 什么是Lifecycle? Lifecycle ......

tomcat里面有各种各样的组件,每个组件各司其职,组件之间又相互协作共同完成web服务器这样的工程。在这些组件之上,lifecycle(生命周期机制)至关重要!在学习各个组件之前,我们需要看看lifecycle是什么以及能做什么?实现原理又是怎样的?

什么是lifecycle?

lifecycle,其实就是一个状态机,对组件的由生到死状态的管理。

  • 当组件在starting_prepstartingstarted时,调用start()方法没有任何效果
  • 当组件在new状态时,调用start()方法会导致init()方法被立刻执行,随后start()方法被执行
  • 当组件在stopping_prepstoppingstopped时,调用stop()方法没有任何效果
  • 当一个组件在new状态时,调用stop()方法会将组件状态变更为stopped,比较典型的场景就是组件启动失败,其子组件还没有启动。当一个组件停止的时候,它将尝试停止它下面的所有子组件,即使子组件还没有启动。

lifecycle方法

我们看看lifecycle有哪些方法,如下所示:

public interface lifecycle {
    // 添加监听器
    public void addlifecyclelistener(lifecyclelistener listener);
    // 获取所以监听器
    public lifecyclelistener[] findlifecyclelisteners();
    // 移除某个监听器
    public void removelifecyclelistener(lifecyclelistener listener);
    // 初始化方法
    public void init() throws lifecycleexception;
    // 启动方法
    public void start() throws lifecycleexception;
    // 停止方法,和start对应
    public void stop() throws lifecycleexception;
    // 销毁方法,和init对应
    public void destroy() throws lifecycleexception;
    // 获取生命周期状态
    public lifecyclestate getstate();
    // 获取字符串类型的生命周期状态
    public string getstatename();
}

lifecyclebase

lifecyclebaselifecycle的基本实现。我们逐一来看lifecycle的各个方法。

增加、删除和获取监听器

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);
}
  1. 生命周期监听器保存在一个线程安全的list中,copyonwritearraylist。所以add和remove都是直接调用此list的相应方法。
  2. findlifecyclelisteners返回的是一个数组,为了线程安全,所以这儿会生成一个新数组。

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);
        // 初始化,该方法为一个abstract方法,需要组件自行实现
        initinternal();
        // 初始化完成之后,状态变更为`initialized`
        setstateinternal(lifecyclestate.initialized, null, false);
    } catch (throwable t) {
        // 初始化的过程中,可能会有异常抛出,这时需要捕获异常,并将状态变更为`failed`
        exceptionutils.handlethrowable(t);
        setstateinternal(lifecyclestate.failed, null, false);
        throw new lifecycleexception(
                sm.getstring("lifecyclebase.initfail",tostring()), t);
    }
}

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) {
        // must have been triggered by one of the abstract methods (assume
        // code in this class is correct)
        // null is never a valid state
        // state不允许为null
        if (state == null) {
            invalidtransition("null");
            // unreachable code - here to stop eclipse complaining about
            // a possible npe further down the method
            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);
    }
}

我们看看firelifecycleevent方法,

public void firelifecycleevent(string type, object data) {
    // 事件监听,观察者模式的另一种方式
    lifecycleevent event = new lifecycleevent(lifecycle, type, data);
    lifecyclelistener interested[] = listeners;// 监听器数组 关注 事件(启动或者关闭事件)
    // 循环通知所有生命周期时间侦听器
    for (int i = 0; i < interested.length; i++)
        // 每个监听器都有自己的逻辑
        interested[i].lifecycleevent(event);
}

 首先, 创建一个事件对象, 然通知所有的监听器发生了该事件.并做响应.

start()

@override
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前的状态设置
        setstateinternal(lifecyclestate.starting_prep, null, false);
        // start逻辑,抽象方法,由组件自行实现
        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 {
            // 设置状态为started
            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);
    }
}

stop()

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

    // stop()的执行,必须要是`started`和`failed`
    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);
        }

        // stop逻辑,抽象方法,组件自行实现
        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) {
        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();
        }
    }
}

destroy()

@override
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.warn(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前状态设置
        setstateinternal(lifecyclestate.destroying, null, false);
       // 抽象方法,组件自行实现
        destroyinternal();
        // destroy后状态设置
        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);
    }
}

模板方法

从上述源码看得出来,lifecyclebase是使用了状态机+模板模式来实现的。模板方法有下面这几个:

// 初始化方法
protected abstract void initinternal() throws lifecycleexception;
// 启动方法
protected abstract void startinternal() throws lifecycleexception;
// 停止方法
protected abstract void stopinternal() throws lifecycleexception;
// 销毁方法
protected abstract void destroyinternal() throws lifecycleexception;

总结

lifecycle其实非常简单,代码也不复杂,但是剖析其实现对于我们理解组件的生命周期有很大的帮助,也有助于我们对设计模式的回顾。