When client request comes a seperate thread is created by the Container along with a new request and response object. It is said that it is wrong to say that multiple instances are created for each request.
I am confused that if for each new client request a new request and response objects are created then are they referred to same instance which was created earlier? And does it happen for only single client?
Do let me know if there is a complete different picture.
"new client request" means the request is new, not the client. Every time a request comes in, new request/response object is created and once the response (e.g. html or image etc) is sent to the client (e.g. browser) the request/response is destroyed.
It means that for each new request, a thread is created with new request and response objects and these separate thread operate on the same instance of the servlet. They meant to say that there is only one instance of the servlet with multiple threads operating on them. That is why you should be careful in using the instance variables in the servlet class.
posted 11 years ago
Thanks for your answers.
@Thiyanesh - Would you please let me know what do you mean by "You should be careful using instance variables in servlet class".
He means that you should not use member variables, because there's one servlet for multiple threads. ThreadA could update varA of servletA while ThreadB is reading the same variable of the same servlet, giving unexpected results.
Yes and No Avoid the use of instance variables. There was something called "The Single Thread Model", but it's been deprecated. Synchronizing a block of code would still be acceptable though. Other means could be to put values into the response, or the session, or the application context.