| 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 ]
|
 |
 |
|
|
subject: instance variable in helper class is thread safe ?
|
|
|