A brief analysis of the life cycle management of Tomcat

Source: Internet
Author: User
Tags tomcat server

In the previous article: the Tomcat server top-level architecture and startup process has a general understanding of Tomcat's overall architecture, which is primarily to learn about Tomcat's entire lifecycle management.

Tomcat lifecycle management uses the Observer model to make Tomcat's lifecycle management mechanism very elegant, and when Tomcat starts, only one server component needs to be started, all containers and corresponding components are started, and the listener for those containers is triggered, Completes the setup of the startup process. It can be said that "one-click" Start. The same is true of the stop process. A brief description of the Observer model

(1) The observer pattern is sometimes referred to as the Publish/subscribe model, where the Observer pattern defines a one-to-many dependency that allows multiple observer objects to simultaneously listen to a Subject object. When the state changes, the subject object notifies all the observer objects so that they can automatically update themselves.

The application of the observer pattern is extensive, such as the Java AWT event model, the servlet listener, the spring event handling mechanism, and the Tomcat lifecycle management mechanism, among others.

(2) The problem that the Observer pattern solves

Splitting a system into classes that collaborate with one another has a bad side-effect of maintaining consistency among related objects. We don't want to keep all kinds of tight coupling in order to maintain consistency, which can be inconvenient for maintenance, expansion, and reuse. The observer is the solution to this kind of coupling relationship.

(3) There are 3 types of role objects in the Observer model:

1. Abstract theme (Subject): It saves the references of all observer objects to a single aggregation, each subject can have any number of observers. Abstract topics provide an interface for adding and deleting observer objects.

2, the specific theme (ConcreteSubject): The state of the specific observer to the object, in the specific subject of changes in the internal state, to all registered observers to send notice.

3. Abstract Observer (Observer): Define an interface for all specific observers and update themselves when subject notification is received.

4. Specific observer (Concreteobserver): Implements the update interface required by the abstract observer role to harmonize its own state with the subject state.
  
(4) The class diagram of the Observer pattern:
second, Tomcat lifecycle management-related classes

The related classes involved in Tomcat lifecycle management include:

(1) Lifecycle: equivalent to abstract theme roles, all container classes and component implementation classes implement this interface. such as Standardcontext

(2) Lifecyclelistener: the equivalent of the abstract observer role, the specific implementation class has Contextconfig, Hostconfig, Engineconfig class, they are triggered when the container starts and stops.

(3) Lifecycleevent: Lifecycle events that encapsulate themes and events that occur.

(4) Lifecyclesupport: A practical class of lifecycle management that provides methods for adding, deleting, and notifying observers. (This is not used in Tomcat release version 9.0.x)

(5) Lifecycleexception: Life cycle anomaly class. Three, lifecycle interface introduction

Generic interface for component lifecycle methods. Org.apache.catalina.Lifecycle Tomcat unifies the lifecycle through the lifecycle interface, and all life-cycle components implement the lifecycle interface to provide a consistent mechanism to start and stop components. Lifecycle interface contents are as follows:

As you can see in the diagram above, the lifecycle interface does four things:

(1) 13 string constants are defined: These constant information is used in the type attribute of the Lifecycleevent event, which distinguishes the state of the Lifecycleevent event emitted by the component (for example, before initialization, before booting, starting medium). This design method allows multiple states to send the same type of time, and then uses one of the attribute classes to distinguish between States without defining multiple events.

(2) A method that defines 3 management listeners: Addlifecyclelistener, Findlifecyclelisteners, and Removelifecyclelistener. Used to add, find, and delete listeners of the Lifecyclelistener type, respectively. Source code as shown in the following figure:

(3) A method that defines 4 Life cycles: init, start, stop, and destory, which are used to perform various stages of the lifecycle, and the interface is defined as follows:

public void Init () throws lifecycleexception;

public void Start () throws lifecycleexception;

public void Stop () throws lifecycleexception;

public void Destroy () throws lifecycleexception;

(4) Defines two methods for obtaining the current and state: GetState and Getstatename, which are used to get the current state, GetState return value Lifecyclestate is an enumeration type, which enumerates the nodes of the lifecycle. The Getstatename method returns the name of a string type state.

The complete Lifecycle Interface definition code is as follows:

Package Org.apache.catalina;
    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 (); Public interface SingleUse {}}
Iv. Lifecycle Interface default implementation Lifecyclebase

The default implementation of the lifecycle interface is Org.apache.catalina.util.LifecycleBase, which implements the method defined in the lifecycle interface in the Lifecyclebase implementation class, which is shown in the following class structure diagram:

(1) 3 ways to manage listeners

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

You can see that lifecyclebase defines a lifecyclelisteners set to hold all listeners, and then defines ways to add, remove, find, and execute listeners;

(2) 4 Life cycle methods: Init, start, stop, and Destory

protected abstract void Initinternal () throws lifecycleexception;

    @Override public
    final synchronized void init () throws Lifecycleexception {
        // The starting state must be lifecyclestate.new, otherwise it throws an exception
        if (!state.equals (lifecyclestate.new)) {
            invalidtransition ( lifecycle.before_init_event);
        }

        try {
            //before initializing, setting the status to Lifecyclestate.initializing means initializing
            setstateinternal (lifecyclestate.initializing, NULL, FALSE);
            Use a template for specific initialization, which is
            initinternal () implemented by subclasses;
            After initialization, the state is set to lifecyclestate.initialized to represent initialization completion
            setstateinternal (lifecyclestate.initialized, NULL, false);
        catch (Throwable t) {
            handlesubclassexception (t, "Lifecyclebase.initfail", toString ());
        }
    

Here for the four lifecycle, only the Init method is discussed, and the other three are roughly the same.

The corresponding template method is called in the Init Method Initinternal () The method does not have a specific implementation, but the subclass is implemented specifically, so for subclasses, the way to execute the lifecycle is: initinternal, startinternal, Stopinternal, destroyinternal;

(3) Defines the two methods for obtaining the current and state: GetState and Getstatename

Private volatile lifecyclestate state = lifecyclestate.new;

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

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

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

The State property has been set in the corresponding method of the lifecycle, so the two methods can be used to get the state simply. talking about the Observer model in Tomcat

Observer mode in Tomcat:

Lifecycle in Tomcat is an abstract subject.

Then, such container objects as Standardengine, Standardhost, Standardcontext, standardserver, are specific themes.

Lifecyclelistener defines the method that the observer wants to execute. As mentioned earlier, if the observer is interested in a particular action of the subject, he will do his own action, and this action is the method in the Lifecyclelistener. Of course Lifecyclelistener is an interface where users can define a variety of specific observers.

Tomcat has extended the observer pattern well, adding a lifecyclesupport instead of a theme to manage multiple observers, a clearer feature module, and an array of Lifecyclelistener defined in Lifecyclesupport. When an action occurs in a topic, lifecyclesupport iterates through the array and calls each listener as a method.

The following method is Lifecyclesupport to notify each Lifecyclelistener that an event has occurred.

/**
     * Notify All Lifecycle event listeners that a particular event has
     * occurred to this Container.  The default implementation performs
     * This notification synchronously using the calling thread.
     * 
     @param type Event Type
     * @param data event data *
    /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);

    }

Tomcat defines events as Lifecycleevent

/**
     * Construct a new lifecycleevent with the specified parameters.
     *
     * @param lifecycle Component on which this event occurred
     * @param type Event type (required)
     * @param data Event data (if any)
     */Public
    lifecycleevent (Lifecycle Lifecycle, String type, Object data) {
        super ( Lifecycle);
        This.type = type;
        This.data = data;
    }

Event has an attribute type that identifies the type of event.

That is to say, Tomcat's Observer mode flow:

1, add the Observer listener to the listener array of Lifecyclesupport

2, when container (theme) to do some action, will generate a Lifecycleevent object, this object indicates what the current action is an event, Lifecyclesupport then notifies each observer in the listener array of the occurrence of the event.

3, Listener will judge the type of event according to Lifecycleevent, complete the corresponding action.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.