JSP Servlet Thread Safety

S

Scotchy

I have a probably simple question from which I have been unable to answer.
If servlets are reusable are they thread safe? For example if I am
processing 5 customers all at the same time using the same servlet do I need
to be careful what I store in vars within a class object? Given the pseudo
code below...

public class multiuserservlet extends servlet
{
HttpRequest req=null;
String username="";
public multiUserServlet () {
//Empty constructor
}

public multiUserServlet (HttpRequest request,String uname) {
this.req=request;
this.username=uname;
}

public void DoSomething() {
//Look at the req object here
//do something with username
username+=" Buddy";
}

public void DoSomething(HttpRequest req) {
//Look at the req object here
//do something with username
username+=" Buddy";
}

}

Which DoSomething method is safer or does it matter? I have read numerous
JSP books some of them say it is not safe but doesn't describe why it is not
safe. Is it a question of context switching within the JSP engine? BTW I
am using the latest version of Apache,Tomcat, and J2SE

Thanks for your help
Scotchy
 
R

Ryan Stewart

Scotchy said:
I have a probably simple question from which I have been unable to answer.
If servlets are reusable are they thread safe?
[...]
You should read up on the Java code conventions and also attempt to
post compilable code. In answer to your question, here is a quote from
the Servlet spec:
"SRV.2.3.3.1 Multithreading Issues
A servlet container may send concurrent requests through the service
method of the servlet. To handle the requests the developer of the
servlet must make adequate provisions for concurrent processing with
multiple threads in the service method."

Therefore, any threading issues you might have with any other class can
occur in a Servlet.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top