• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads and instance variables

 
Brian Nice
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have many servlet threads that use the same action object (like how Struts works), and the servlet threads call the action class's processRequest method. This method is Thread safe as it only uses variables local to the processRequest method.
Now, if inside this method I create a new object, say B(), and B has instance variables that are being modified, will that cause a problem? Or since B is being called from inside a thread-safe method in my action object, will it not matter?
Hope that makes sense. Thanks for the help
Brian
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should be just fine. Every thread gets a new instance of B when they do new B() and each instance of B can do whatever it wants. This is a perfectly common sense way around the whole thread-safe-servlet issue: delegate work to a helper object. Of course J2EE reuses a single servlet instance to avoid a lot of object creation and gc, and this just kind of wipes out whatever they gained there. I feel bad when I do it, but I do it.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you create the object from inside the method, and manipulate it only inside the method where it's created, then it will only be accessed by one thread -- the one that called that method -- so there will be no thread-related problems.
On the other hand, if that object you create is stored in some globally accessible place, such that multiple simultaneous method invocations might use that object, then there may be a problem with thread safety.
Does this answer your question?
 
Brian Nice
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, thanks for the help! That clears things up for me.
Brian
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!