Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance variable in helper class is thread safe ?

 
mike zhang
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic