Servlet Life Cycle
Servlet life cycle is well defined, and exposed through lifecycle methods init, service and destroy. Using Servlet Life methods we customize the behavior of a servlet.
The init() method :-
As per servlet doc , init() method is called by the servlet container to indicate to a servlet that the servlet is being placed into service.
The servlet container calls the init
method exactly once after instantiating the servlet.
The init method must complete successfully
before the servlet can receive any requests.
The service() method :-
service() method is only called after the servlet's init() method has completed successfully.
Servlets typically run inside multithreaded servlet containers
that can handle multiple requests concurrently. Developers must
be aware to synchronize access to any shared resources such as files,
network connections, and as well as the servlet's class and instance
The destroy() method :-
Called by the servlet container to indicate to a servlet that the
servlet is being taken out of service. This method is
only called once all threads within the servlet's
service method have exited or after a timeout
period has passed. After the servlet container calls this
method, it will not call the service method again
on this servlet.
This method gives the servlet an opportunity
to clean up any resources that are being held (for example, memory,
file handles, threads) and make sure that any persistent state is
synchronized with the servlet's current state in memory.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Servlet Life Cycle Code : -