Local variables in a method are thread-safe. There is no way another thread can change them. But beware of local variables that are object references. The object reference is thread-safe, but the object that it points to may be shared between threads, depending on who else has got a reference to the object.
ThreadLocal objects and many classes in the concurrency package (Java 5+) are thread-safe. That's rather their raison d'etre.
Some other API objects are thread-safe, to some extent. However, as in the case of Vector and Hashtable, this may only mean that their internal state cannot get messed-up by being shared between threads. If the "thread-safe" object is part of a larger structure, then that structure is not thread-safe unless additional precautions are taken.
Being static or non-static has little bearing on whether a field is thread-safe. Non-static fields can certainly be shared between threads.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Joined: May 15, 2005
can you please give me a example of not static variable being thread safe. And secondly are the instance variables in the thread class(the one in my first post) is thread safe?
Now I've shared my variable with two other threads. They can easily get into race conditions.
Say MyRunnable did this:
That could print true or false because the other thread might be setting it to 42 in between lines. If MyRunnable is to be thread safe, it must enclose any two calls where it expects consistent state in synchronized blocks. If I put those two lines in a synchronized(sharedArgument) block then I know that won't happen.
Is that making sense so far? Try the Sun Concurrency Tutorial for more good stuff.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi