wood burning stoves 2.0*
The moose likes Servlets and the fly likes instance variable in helper class is thread safe ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "instance variable in helper class is thread safe ?" Watch "instance variable in helper class is thread safe ?" New topic
Author

instance variable in helper class is thread safe ?

mike zhang
Ranch Hand

Joined: Feb 26, 2002
Posts: 59
I know the instance variables in a servlet are NOT thread safe, in the following code:
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ... {
Helper_1 help_1 = new Helper_1();
help_1.doIt();
}
}
****
import javax.servlet.*;
public class Helper_1 {
private Helper_2 help_2;
public void doIt(HttpServletRequest req, HttpServletResponse res) {
help_2 = new Helper_2();
help_2.setValue();
help_2.getValue();
}
}
****************************
public class Helper_2 {
.... // a non-servlet class here
}
*****************************
I defined "help_2" as a class instance varibale.
My thought is: Since "help_1" is thread safe, and "help_2" is a private instance variable of "help_1" so I don't need to worry about the thread safe issue for "help_2", is that right ?
Thanks,
Mike
Christopher Dixon
Greenhorn

Joined: Jan 30, 2002
Posts: 22
You've got it. Since every call to doGet(req, resp) is a seperate thread, and the variable help_1 is declared as a local variable in the method doGet(req, resp), each thread has it's own help_1 and instance of Helper_1.
help_2 is fine (used as in your example) since no threads will be sharing an instance of Helper_1, they each have their own.
HTH,
Chris
[ March 04, 2002: Message edited by: Christopher Dixon ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instance variable in helper class is thread safe ?
 
Similar Threads
Is this thread safe ?
thread safe
Single Thread Model
SingleThreadModel Servlet with class variable
Thread safe