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.
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
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