File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

are instance variables thread safe ?

 
Javed Sardar
Ranch Hand
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you declare your Vector to be static? If yes that might be the problem.
Jawad
 
Bruce Jin
Ranch Hand
Posts: 672
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instance variables are thread safe because all clients use the same instance.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13045
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7292
Netbeans IDE VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic