Take the 2-minute tour ×

Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am getting the servlet context and setting session variables. Now, if 2 or more users send request to this server then what happens to the session variables? Will they all be common for all the users or they will be different for each user. If they are different, then how was the server able to differentiate between different users?

One more similar question, if there are n users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately?

share|improve this question
add comment

6 Answers

up vote 654 down vote accepted


When the servletcontainer (like Apache Tomcat) starts up, it will deploy and load all webapplications. When a webapplication get loaded, the servletcontainer will create the ServletContext once and keep in server's memory. The webapp's web.xml will be parsed and every Servlet, Filter and Listener found in web.xml will be created once and kept in server's memory as well. When the servletcontainer shuts down, it will unload all webapplications and the ServletContext and all Servlet, Filter and Listener instances will be trashed.

HttpServletRequest and HttpServletResponse

The servletcontainer is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 80. When a client (user with a webbrowser) sends a HTTP request, the servletcontainer will create new HttpServletRequest and HttpServletResponse objects and pass it through the methods of the already-created Filter and Servlet instances whose url-pattern matches the request URL, all in the same thread.



When a client visits the webapp for the first time and/or the HttpSession is to be obtained for the first time by request.getSession(), then the servletcontainer will create it, generate a long and unique ID (which you can get by session.getId()) and store it in server's memory. The servletcontainer will also set a Cookie in the HTTP response with JSESSIONID as cookie name and the unique session ID as cookie value.

As per the HTTP cookie specification (a contract a decent webbrowser and webserver has to adhere), the client (the webbrowser) is required to send this cookie back in the subsequent requests as long as the cookie is valid. Using a HTTP header checker tool like Firebug you can check them. The servletcontainer will determine every incoming HTTP request header for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.

The HttpSession lives until it has not been used for more than the <session-timeout> time, a setting you can specify in web.xml, which defaults to 30 minutes. So when the client doesn't visit the webapp anymore for over 30 minutes, then the servletcontainer will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servletcontainer will create a new one.


In a nutshell

  • The ServletContext lives as long as the webapp lives. It's been shared among all requests in all sessions.
  • The HttpSession lives as long as the client is interacting with the webapp with the same browser instance and the session hasn't timed out at the server side yet. It's been shared among all requests in the same session.
  • The HttpServletRequest and HttpServletResponse lives as long as the client has sent it until the complete response (the webpage) is arrived. It is not being shared elsewhere.
  • Any Servlet, Filter and Listener lives as long as the webapp lives. They are being shared among all requests in all sessions.
  • Any attribute which you set in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives.


That said, your major concern is possibly threadsafety. You should now have learnt that Servlets and filters are shared among all requests. That's the nice thing of Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise have been too expensive to recreate it on every request.

But you should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's threadunsafe! The below example illustrates that:

public class MyServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

        Object thisIsThreadSafe;


See also:

share|improve this answer
So when I somehow can find out the JSessionId which gets send to a client, I can steal his session? –  Toskan Nov 30 '11 at 13:37
@Toskan: that's correct. It's known as session fixation hack. Please note that this is not specific to JSP/Servlet. All other server side languages which maintains the session by a cookie are sensitive as well, like PHP with PHPSESSID cookie, ASP.NET with ASP.NET_SessionID cookie, etcetera. That's also why URL rewriting with ;jsessionid=xxx as some JSP/Servlet MVC frameworks automatically do is frowned upon. Just make sure that session ID is never exposed in URL or by other means in webpages so that the unaware enduser won't be attacked. –  BalusC Nov 30 '11 at 13:45
@Toskan: Also, make sure that your webapp is not sensitive to XSS attacks. I.e. do not redisplay any user-controlled input in unescaped form. XSS put doors open to ways to collect session IDs of all endusers. See also What is the general concept behind XSS? –  BalusC Nov 30 '11 at 13:48
@BalusC: Do all servlets loaded at startups? I hear it was when the first request is received the servlet is loaded. Please clarify. –  itsraja Feb 6 '12 at 16:39
add comment

Session in Java servlets is the same as session in other languages such as PHP. It is unique to the user. The server can keep track of it in different ways such as cookies, url rewriting etc. This Java doc article explains it in the context of Java servlets and indicates that exactly how session is maintained is an implementation detail left to the designers of the server. The specification only stipulates that it must be maintained as unique to a user across multiple connections to the server. Check out this article from Oracle for more information about both of your questions.

Edit There is an excellent tutorial here on how to work with session inside of servlets. And here is a chapter from Sun about Java Servlets, what they are and how to use them. Between those two articles, you should be able to answer all of your questions.

share|improve this answer
This brings up another question for me, Since there is only one servlet context for the whole application and we get access to the session variables through this servletcontext so how can the session variables be unique to every user? Thanks.. –  Ku Jon Jun 24 '10 at 1:27
how are you accessing the session from the servletContext? You're not referring to servletContext.setAttribute(), are you? –  matt b Jun 24 '10 at 1:44
oh man... request.getSession()! RTFM! –  Vladimir Dyuzhev Jun 24 '10 at 2:16
add comment

Sessions - what Chris Thompson said.

Instantiation - a servlet is instantiated when the container receives the first request mapped to the servlet (unless the servlet is configured to load on startup with the <load-on-startup> element in web.xml). The same instance is used to serve subsequent requests.

share|improve this answer
add comment

When the servletcontainer (like Apache Tomcat) starts up, it will read from web.xml file (only one per application)if any thing goes wrong shows up error at container side console or it will deploy and load all webapplications by using web.xml (so named it as deployment descriptor).

During instantiation phase of servlet ,servletInstance is ready but it cannot serve the client request because it is missing with two pieces of information 1:context information 2:initial configuration information Servletengine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of servlet by suplying servletconfig object references as argument.Once init() is completedly executed servlet is ready to server the client request.

Q) In the life time of servlet how many times instantiation and initaialization happens ??

A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie,after serving one client request server does not die.It waits for other client requests ie what CGI(for every client request a new process is created) limitation is overcome with servlet(internally servlet engine creates thread)

Q)How session concept works?

A)whenever getSession() is called on HttpServletRequest object

Step 1:request object is evalauated for incoming session ID

Step 2:if ID not avaiable a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to servlet (doGet/doPost).

Step 3:if Id avaiable brand new session object is not created session id is picked up from the request object search is made in the collection of sessions by using session ID as the key Once the search is sucessful session id is stored into HttpServletResponse and the exsisting session object references is returned to the doGet or doPost() of UserDefineservlet.


1)when control leaves from servlet code to client dont forget that session object is being hold by servletcontainer ie, servletengine

2)multithreading is left to servlet devlopers people for implementing ie., handle the multiple request of client nothing to bother about multithread code

Inshort form:

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.

share|improve this answer
add comment


enter image description here enter image description here

In short: the web server issues a unique identifier to each visitor on his first visit. The visitor must bring back that ID for him to be recognised next time around. This identifier also allows the server to properly segregate objects owned by one session against that of another.

Servlet Instantiation

If load-on-startup is false:

enter image description here enter image description here

If load-on-startup is true:

enter image description here enter image description here

Once he's on the service mode and on the groove, the same servlet will work on the requests from all other clients.

enter image description here

Why isn't it a good idea to have one instance per client? Think about this: Will you hire one pizza guy for every order that came? Do that and you'd be out of business in no time.

It comes with a small risk though. Remember: this single guy holds all the order information in his pocket: so if you're not cautious about thread safety on servlets, he may end up giving the wrong order to a certain client.

share|improve this answer
+1 for amazing easily understandable pics. :) –  eRRor 404 Jan 17 at 9:08
add comment

The Servlet Specification JSR-315 clearly defines the web container behavior in the service (and doGet, doPost, doPut etc.) methods ( Multithreading Issues, Page 9):

"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 serializing 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 that the application is 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".

share|improve this answer
add comment

protected by AVD Jun 6 '12 at 10:02

