This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Q: what should you use if you need mutliple instances of the servlet to share something?
A: if you want all the threads to access a value, decide which attribute state makes the most sense, and store the value in an attribute.
chances are, you can solve your problems in one of the two ways:
1)Declare the variables as local variable within the service method, rather than as an instance variable.
2) use an attribute in the most appropriate scope.
my Question is
since we do not overwrite the service() method, how could we declare the variables in the service() mehtod, or does the answer in the book means
declare the variables in the DoGet or DoPost method of my Servlet class?
the second approach which is use an attribute, in that case if the attribute is context-attribute or session attribute, I will have to synchronize the
servletContext and httpSession object as well, is that correct?
since we do not overwrite the service() method, how could we declare the variables in the service() mehtod
You could override it. But I don't get it either. How could a variable be shared if it was local to a method ? It doesn't make sense.
the second approach which is use an attribute, in that case if the attribute is context-attribute or session attribute, I will have to synchronize the servletContext and httpSession object as well, is that correct?
You will have to do some sort of synchronization indeed.
First of all there is no multiple instance of same Servlet. If more clients are accessing the Servlet then the container will create a thread for every request.
To answer your 1st question,
you can define that common variable in Web.XML which you want to share under <context-param> tag that way it will be shared by different client.
But if you use HttpSession it won't be shared by different Client but it will be shared by same client for different request.
for example Client opened a browser and hitting the servlet and the same client opened another browser hitting the servlet again.
To answer your point (1):
If you declare the variable in service method or accessing a property using HttpServeltRequest getParameter() method inside the service method it won't be shared by any thread at all. So it means no instance will be shared. these are thred safe by default.
But Session and application scope are not thread safe.