aspose file tools*
The moose likes Servlets and the fly likes are instance variables thread safe ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "are instance variables thread safe ?" Watch "are instance variables thread safe ?" New topic
Author

are instance variables thread safe ?

Javed Sardar
Ranch Hand

Joined: Sep 10, 2002
Posts: 33
Are instance variables thread safe ? I have a servlet in which I have a vector as an instance variable.
When one clinet fills the data in the vector which is intially null, I expect another client to get null and not the vector with data. But Iam wrong. Second client is getting a vector filled with data.
Where am I missing. I am using iPlanet4.1 web server
Regards,
Javed.
Jawad Kakar
Ranch Hand

Joined: Oct 06, 2002
Posts: 82
Did you declare your Vector to be static? If yes that might be the problem.
Jawad
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 671
instance variables are thread safe because all clients use the same instance.


BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12823
    
    5
ARG!! How many times do we have to say this!!
Instance variables are shared by all requests therefore are NOT inherently Thread safe. Without special precautions, any number of requests could be modifying that Vector "at the same time."
It is local variables that are Thread safe.
Bill
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

Thread safety is easier to understand when looking at bytecode. Even individual lines of code in a Java function rarely correspond to a single bytecode instruction.
Pre-empting a thread can happen, at least in theory, between any two bytecode instructions -- even, in some cases, "during" one. It may be unlikely that one thread interrupts another in such a way that it corrupts data, but it's possible, and that's what you have to defend against.
To prove this, don't have one client fill the data and one get it -- have multiple clients send different strings of data, and get the value from another client "at the same time." Over enough trials, you'll see a value that's been messed up by failure to synchronize the action.
Instance variables, just to be persnickety, are neither threadsafe or threadunsafe. It's the methods that manipulate an instance variable without protecting it that makes it vulnerable to corruption.


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: are instance variables thread safe ?