This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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 REST with Spring (video course) this week in the Spring 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

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();
import javax.servlet.*;
public class Helper_1 {
private Helper_2 help_2;
public void doIt(HttpServletRequest req, HttpServletResponse res) {
help_2 = new Helper_2();
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 ?
Christopher Dixon

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.
[ March 04, 2002: Message edited by: Christopher Dixon ]
It is sorta covered in the JavaRanch Style Guide.
subject: instance variable in helper class is thread safe ?
It's not a secret anymore!