Re: Member variables within servlet application - are they threadsafe?
"Simon Eichenauer" <simon@bogar.de> wrote in message
news:f5pdb7$7nc$1@tamarack.fernuni-hagen.de...
| Hi,
|
| I?ve got a question about thread safety within servlet applications.
| I know that, for example within a servlet or a struts action, you
| shouldn?t use member variables because within the virtual machine
| only one instance of each servlet / action exists (or at least the member
| variables exist only once and aren?t put on the thread stack). But what
| about member variables declared within
| classes that are used within servlet or action methods? Are they
threadsafe?
| For example:
|
| Action
| execute() {
|
| Test test = new Test();
| test.setMemberVariable("test");
| }
|
| Class Test {
| private String member; // Threadsafe ???
|
| public void setMemberVariable(String test) {
| member = test;
| }
| }
|
| Maybe it?s really stupid but I just couldn?t find any hint.
Your new test object's reference is held locally to the thread and if you do
not allow the reference to be stored where it could be accessed by another
thread, the object will be threadsafe because other threads cannot access
it. Its methods will only be activated from the original thread. If you
store the reference in some structure that is accessible to other threads
(static variables, servlet instance variables, any data structure referenced
by a servlet instance variable, etc,) you expose it to being used by two
threads at the same time. In short, you can't determine threadsafety by
looking at the class--you have to look at how its used.
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/