26

Basically, how long is an instance of a servlet around for? I am kind of guessing it is session scope. However, I suppose it could have some sort of timeout or garbage collection to remove old instances.

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
GC_
  • 1,673
  • 6
  • 23
  • 39
  • I mean instance of a servlet. If I have 5 users using the "same" servlet, but different instances. However, I guess fomr the comments that is not true. – GC_ Oct 08 '10 at 20:43
  • Related: http://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables – BalusC Oct 08 '10 at 23:21

11 Answers11

40
  • a servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting)
  • when the servlet is instantiated, the init() method of the servlet is called
  • then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet
  • when the application is undeployed (the servlet container stops), the destroy() method is called.
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Why will synchronization mean anything up? I guess It might slow it down, but it doesn't seem like it would cause a dead lock. – GC_ Oct 08 '10 at 21:10
  • 6
    it slows it down massively. This means each user will have to wait for another user to complete the request - unacceptable. – Bozho Oct 08 '10 at 21:21
  • Only one Servelt instance for one Application? If I have 100 requests in the same seconds, they will be all synchronized one after one? – JaskeyLam Jul 18 '14 at 10:31
  • I think a good addition to your answer would be to outline: When (.. or as a result of what event) does the HTTP request's input stream actually get read..? Can it be read by the time service() is called? Does getParameter() call in a Filter result in the read().. (not sure myself to be honest) – johnm Oct 05 '17 at 15:22
15

The lifecycle is well defined, and exposed through lifecycle methods exposed in init, service, and destroy methods of the Servlet.

And, despite what else is being said here, this is all you can count on from the specification. Basically, you get those three methods and a guarantee that Servlets are not thread safe. That a single servlet MAY be simultaneously accessed by one or more requests.

There is nothing in the specification that limits a servlet to one instance the container, if a container decides to, it can get a request, create a servlet, call it's init, then service, then destroy methods, and set it free for garbage collection.

Individual containers have potentially different implementations.

Most containers do create a single instance. But the specification does not guarantee that, so you shouldn't rely on it.

Also, consider something like Google App Engine. GAE is VERY aggressive is continually expiring and shutting down entire web apps that receive no traffic. If you have a lightly traveled site, you can very well expect the entire app to start up, init all of its services, init any load-on-startup servlets, execute the request, and then shut everything down. So, on GAE it's imperative that you have a very fast application startup in order to maintain any semblance of performance.

So, simply, what you can count on is what the specification says. Individual containers may offer different run time experiences.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
5

A Servlet lives as long as the application does.

deamon
  • 89,107
  • 111
  • 320
  • 448
  • It can't be more than session scope. One user can't reference another user's servlet instance. Therefor, servlet instances are tied to session. Is that right? If they are tied to session, I would assume that go away after the session goes away. – GC_ Oct 08 '10 at 20:41
  • 7
    No, Grae - users all use the same servlet instances. – Vetle Oct 08 '10 at 20:44
  • Or am I wrong, maybe different users can share object variables in a HttpServlet. – GC_ Oct 08 '10 at 20:45
  • Just to be clear, object level variables in a HttpServlet, shared between users? – GC_ Oct 08 '10 at 20:46
  • There is only one instance of a particular servlet and all requests that map to that servlet, regardless of user, will go to that instance. Any variables in that instance will, of course, be there as well. – ColinD Oct 08 '10 at 20:54
4

A servlet is not bound to a session, it is a service object that is instantiated by the container when needed, and typically is kept alive for the full life of the webapp. It typically responds to requests from several clients (and sessions), even concurrent requests. That's precisely why your servlet code must be thread safe, and you never store in a servlet field some data associated to a request or a session.

leonbloy
  • 73,180
  • 20
  • 142
  • 190
2

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

  • The servlet is initialized by calling the init () method.
  • The servlet calls service() method to process a client's request.
  • The servlet is terminated by calling the destroy() method.
  • Finally, servlet is garbage collected by the garbage collector of the JVM.

More here ..

http://www.dzone.com/links/r/java_ee_servlets_life_cycle.html

babu
  • 21
  • 1
1

when i remember correctly servlets live as Singletons in the Servlet Container (e.g. Tomcat). Im not sure if the first instantiation is lazy, meaning that the Servlet gets constructed only if needed, but im guessing one could check this in the corresponding Servlet Container's Classloader sources. The Servlet's lifecycle ends and it's destroy() method gets called when the Servlet Container is shut down. You can check this easily by setting up breakpoints or logging in the appropriate init() and destroy() methods and Constructor then just check when the code gets executed in your debugger/logfile.

hope that helped.

References: Tomcat's Classloader howto

fasseg
  • 17,504
  • 8
  • 62
  • 73
  • 1
    The first instance is usually lazy, you can control that in web.xml by setting `1` – nos Oct 08 '10 at 20:42
1

Actually the Servlet may be destroyed and recreated at any time ! So the other answers kinda describe the whole lifecycle but miss this important detail. From the servlet specification:

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 milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between.

[...]

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.

Bat0u89
  • 610
  • 2
  • 17
  • 25
1

The servlet (its one and only instance) will handle n number of request in the fashion of separate single thread for every client ie where CGI limitation is overcomed

A servlet object lives in heap of serverside machine as long as application is undeployed or servletConatiner is shutdown the servlet object will not die.

Technically : servletcontainer holds servletobject and servletobject holds servletConfig object

Servletcontainer can only call the 3 methods of its life cycle 1)init() 2)service() 3)destroy()

Ajay Takur
  • 6,079
  • 5
  • 39
  • 55
0

The lifecycle of a typical servlet running on Tomcat might look something like this:

1.Tomcat receives a request from a client through one of its connectors.

2.Tomcat maps this request to the appropriate Engine for processing. These Engines are contained within other elements, such as Hosts and Servers, which limit the scope of Tomcat's search for the correct Engine.

3.Once the request has been mapped to the appropriate servlet, Tomcat checks to see if that servlet class has been loaded. If it has not, Tomcat compiles the servlet into Java bytecode, which is executable by the JVM, and creates an instance of the servlet.

4.Tomcat initializes the servlet by calling its init method. The servlet includes code that is able to read Tomcat configuration files and act accordingly, as well as declare any resources it might need, so that Tomcat can create them in an orderly, managed fashion.

5.Once the servlet has been initialized, Tomcat can call the servlet's service method to process the request, which will be returned as a response.

6.During the servlet's lifecycle, Tomcat and the servlet can communicate through the use of listener classes, which monitor the servlet for a variety of state changes. Tomcat can retrieve and store these state changes in a variety of ways, and allow other servlets access to them, allowing state to be maintained and accessed by various components of a given context across the span of a single or multiple user sessions. An example of this functionality in action is an e-commerce application that remembers what the user has added to their cart and is able to pass this data to a checkout process.

7.Tomcat calls the servlet's destroy method to smoothly remove the servlet. This action is triggered either by a state change that is being listened for, or by an external command delivered to Tomcat to undeploy the servlet's Context or shut down the server.

Reference:

https://www.mulesoft.com/tcat/tomcat-servlet

15412s
  • 3,298
  • 5
  • 28
  • 38
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/10904345) – Hamad Jan 15 '16 at 10:28
  • 1
    Added more descriptive text – 15412s Jan 15 '16 at 10:34
0
life cycle of servlet >
1) load the class.
2) instantiate the servlet.
3) servlet container construct the servlet config interface.
4) container call the init() and pass the servlet config object.
5) httpRequest and httpResponse object created.
6) container call the service() and pass the httpRequest and httpResponse object as argument.
7) process the service method.and if have any other request then follow the step 4 again.
8) other wise container call the distroy().
Anand Pandey
  • 383
  • 4
  • 12
0

The servlet's container is attached to a web server that listens for HTTP or HTTPS requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (user with a web browser) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects (for every new request) and passes them through any defined Filter chain and, eventually, the Servlet instance.

In the case of filters, the doFilter() method is invoked. When its code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.

In the case of servlets, the service() method is invoked(by multiple threads for different request). By default, this method determines which one of the doXxx() methods to invoke based off of request.getMethod(). If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.

The request object provides access to all of the information about the HTTP request, such as its headers and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made for reuse.

Ritesh Kumar
  • 129
  • 1
  • 7