aspose file tools
The moose likes Threads and Synchronization and the fly likes Threads and instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Threads and instance variables" Watch "Threads and instance variables" New topic
Author

Threads and instance variables

Brian Nice
Ranch Hand

Joined: Nov 02, 2000
Posts: 195
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24045
    
  13

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?


[Jess in Action][AskingGoodQuestions]
Brian Nice
Ranch Hand

Joined: Nov 02, 2000
Posts: 195
Yes, thanks for the help! That clears things up for me.
Brian
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Threads and instance variables
 
Similar Threads
Slap me silly, but...
which data is ThreadSafe ?
Thread Safe Instance Variables
Static Methods with local variables.. Thread Safe?
difference betwen parameters and attributes