Say we started up two threads with the same unsafe object as an argument:
Then the two threads call some method in UnsafeObject:
We can think of two threads running "at the same time" but in truth the JVM runs a few instructions from one thread, then a few instructions from another and so on. One thread might work perfectly by itself. But when two or more are running, the JVM could switch control among threads between lines of code. I might call
and expect the second call to execute line 2, but if another thread changed unsafeVariable in between my two lines of code, the second call might execute lines 3 and 4. Zat make sense?
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
Joined: Jun 10, 2001
This might be too fundamental. Is it an instance per thread or instance for many threads ? if its the latter then what you say is perfect .
Joined: Jul 03, 2001
Hello shiva. The fields of an object can be shared between the threads that are able to access them. On the other way, local variables are only accesed by the thread that is executing the method where they were declared. That is, each thread calling the same method will have its own copy of the variables declared in it. But it that method accesses fields of an object, those fields are shared among all the threads executing that method (and possibly other threads executing other methods accessing the same variables) That abc or xyz are not thread safe depends on their class, not on the instance or static characteristic.
Joined: Jan 29, 2003
Member variables are per object instance. I showed the same instance of UnsafeClass as an argument to two threads, so both threads were looking at one object instance, one member variable instance. That's pretty much the definition of thread-safe or unsafe - how does it behave if two threads work with the same object instance. This kind of thing happens in Servlet containers all the time. The container might have only one instance of a servlet object and pass it to any number of incoming request threads at the same time. It's also common for a main driver thread to spawn a bunch of worker threads and give each worker a reference back to the driver, perhaps to report their progress. Or maybe many threads want to update a window or log. So even if my example was a bit contrived (or a lot contrived) this does happen in the real world often enough to make you want to be careful.