Bored Of Simple Servlet Life Cycle, Here Is, In Detail , The Servlet Life Cycle

       A servlet goes through the well defined life cycle that defines how the sevlet is loaded , instantiated, and is initialized, handles requests from clients, and how the servlet is taken out of the service. This whole life cycle is expressed in the API by the init, service, and destroy methods of the javax.servlet.Servlet interface that all the servlets must implement directly or indirectly through the GenericServlet or HttpServlet abstract class.

Loading and Instantiation :

     Who is responsible for loading and instantiating servlets ? Well , the servlet container will take care about these things. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request.

When the servlet engine is started, needed servlet classes must be located by servlet container. The servlet container loads the servlet classes using the normal Java class loading facilities. The loading may be from a local file system, a remote file system, or other network services.

After loading the servlet class, the container instantiates it for free.

Initialization :

     After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC API - based connections), and perform other one-time activities. The container initializes the servlet instance by calling init method of the servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. This configuration object allows the servlet to access name - value initialization parameters from the Web application's configuration information. The configuration object also gives the servlet access to an object ( implementing the ServletContext interface) that describes the servlet's runtime environment.

Errors Conditions on Initialization :

     During initialization , the servlet instance can throw an UnavailableException or a ServletException . In this case , the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization.

A new instance may be instantiated and initialized by the container after a failed initialization. The exception to this rule is when an UnavailableException indicates a minimum time of unavailability, and the container must wait for the period to pass before creating and initializing a new servlet instance.

Request Handling :

     After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request object of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface.

In the case of an HTTP request, the object provided by the container are of types HttpServletRequest and HttpServletResponse.

Note that a servlet instance placed into service by a servlet container may handle no requests during its life time.

Multithreading Issues :

     A servlet container may send concurrent requests through the service method of the servlet. To handle the requests, the Servlet Developer must make adequate provisions for concurrent processing with multiple threads in the service method.

Although it is not recommended, an alternative for the Developer is to implement the SingleThreadModel interface which requires the container to guarantee that there is only one request thread at a time in the service method. A servlet container may satisfy this requirement by serailizing requests on a servlet, or by maintaining a pool of servlet instances. If the servlet is part of a Web application that has been marked as distributable, the container may maintain a pool of servlet instances in each JVM of the application distributed across.

For servlets not implementing the SingleThreadModel interface, if the service method ( or methods such as doGet or doPost which are dispatched to the service method of the HttpServlet abstract class) has been defined with the synchronized keyword, the servlet container cannot use the instance pool approach, but must serialize requests through it. It is strongly recommended that Developers not synchronize the service method ( or methods dispatched to it) in these circumstances because of detrimental effects on performance.

Exceptions During Request Handling :

    A servlet may throw either a ServletException or an UnavailableException during the service of a request. A ServletException signals that some error occurred during the processing of the request and that the container should take appropriate measures to clean up the request.

An UnavailableException singnals that the servlet is unable to handle requests either temporarily or permanently.

If a permanent unavailability is indicated by the UnavailableException, the servlet container must remove the servlet from service, call its destroy method, and release the servlet instance. Any requests refused by the container by that cause must be returned with a SC_NOT_FOUND (404) response.

If temporary unavailability is indicated by the UnavailableException, the container may choose to not route any requests through the servlet during the time period of the temporary unavailability. Any requests refused by the container during this period must be returned with a SC_SERVICE_UNAVAILBLE (503) response status along with a Retry - After header indicating when the unavailability will terminate.

The container may choose to ignore the distinction between a permanent and temporary unavailability and treat all UnavailableExceptions as permanent, there by removing a servlet that throws any UnavailableException from service.

Asynchronous processing :

     Some times a filter and / or servlet is unable to complete the processing of a request without waiting for a resource or event before generating response. For example, a servlet may need to wait for an available JDBC connection, for a response from remote web service, for a JMS message, or for an application event, before proceeding to generate a response. Waiting within the servlet is an inefficient operation as it is a blocking operation that consumes a thread and other limited resources. Frequently a slow resource such as a database may have many threads blocked waiting for access and can cause thread starvation and poor quality of service for an entire web container.

Servlet 3.0 introduces the ability for asynchronous processing of requests so that the thread may return to the container and perform other tasks. When asynchronous processing begins on the request, another thread or callback may either generate the response and can complete or dispatch the request so that it may run in the context of the container using the AsyncContext.dispatch method. A typical sequencs of events for asynchronous processing is :

1. The request is recieved and passed via normal filters for authentication etc. to the servlet.
2. The servlet processes the request parameters and / or content to determine the nature of the request.
3. The servlet issues requests for resources or data, for example, sends a remote web service request or joins a queue waiting for a JDBC connection.
4. The servlet returns without generating a response.
5. After some time, the requested resource becomes available, the thread handling that event continues processing either in the same thread or by dispatching to a resource in the container using the AsyncContext.

A servlet that has asyncSupported = true, then the application can start asynchronous processing in a seperate thread by calling startAsync method, passing it a reference to the request and response objects, and then exit from the container on the original thread. This means that the response will traverse ( in the reverse order) the same filters (or filter chain) that were traversed on the way in. The response isn't committed till complete method is called on the AsyncContext.

Dispatching from a servlet that has asyncSupported = true to one where asyncSupported is set to false is allowed. In this case, the response will be committed when the service of the servlet that does not support async is exited, and it is the container's responsibility to call complete on the AsyncContext so that any interested AsyncListener instances will be notified. Dispatching from a synchronous servlet to an asynchronous servlet would be illegal.

End of Service : 

    The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milli seconds, for the lifetime of the servlet container ( which could be a number of days, months, or years), or any amount of time in between.

When the servlet container determines that a servlet should be removed from service, it calls the destroy method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state. For example, the container may do this when it wants to conserve memory resources, or when it is being shut down.

Befor the servlet container calls the destroy method, it must allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a server - defined time limit.

Once the destroy method is called on a servlet instance, the container may not route other requests to that instance of the servlet. If the container needs to enable the servlet again, it must do so with a new instance of the servlet's class.

After the destroy method completes, the servlet container must release the servlet instance so that it is eligible for garbage collection.


Post a Comment