Jeetandra Mahtani wrote:
> Hello,
> Can someone please confirm the following and maybe provide some insight to make my
> concepts thorough.
> If there are no instance variables and only local variables, one does not need to
>worry
> about different threads accessing the same variable, right?
In the simple cases, this statement is correct. Each thread has its own copy of the
variables that are local (because they are on the stack for that thread), so they are
not
shared.
The developer still needs to remember, though, that objects you reference through local
variables might still be shared, unless you created them with a "new" operator. For
example, the following code creates local variables called "session" and "sb":
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
HttpSession session = req.getSession(true);
StringBuffer sb = new StringBuffer();
... more code here ...
}
but the actual "session" object, and the variables it contains that you access with
getValue() and putValue(), are still shared. The "sb" variable, on the other hand, is
truly unshared, as long as you don't pass it to some method that saves a reference to
it
that is visible to some other thread.
>
> If only local variables are being used in all classes, does one need to worry about
> synchronization/thread issues?
As illustrated above, using only local variables does not solve all of your problems --
only the problem of shared instance variables.
>
> When does one need to use the SingleThread Model ?
In my opinion, the answer to this question is "never", unless your servlet is so self
contained that it makes no references at all to the rest of the world.
SingleThreadModel does help you if you want to use instance variables in your servlet
classes. However, it does nothing at all to solve the problem of simultaneous access
to
shared information -- the problem with the session variable (and its contents) being
shared in the example above still occurs, even if this servlet were declared
SingleThreadModel.
>
> Thanks for any information.
I suggest that you review books and tutorials on how multithreading works in Java, and
focus on learning the proper usage of the "synchronized" modifier, and other techniques
for protecting information against simultaneous modifications.
>
> J
>
Craig McClanahan
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html