Member variables within servlet application - are they threadsafe?

S

Simon Eichenauer

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.

Regards,
Simon
 
M

Matt Humphrey

| 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 (e-mail address removed) http://www.iviz.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top