Reputation: 5836
I declared a instance variable as voltile. Say two threads are created by two processors under multi core where thread updates the variable. To ensure instantaneous visibilty, I believe declaring variable as volatile is right choice here so that update done by thread happens in main memory and is visible to another thread . Right?
Intention here to understand the concept in terms of multicore processor.
Upvotes: 0
Views: 235
Reputation: 34638
It doesn't matter if it's done by different processors or not. When you don't have mult-processors, you can still run into concurrency problems because context switches may happen any time.
If a field is not volatile, it may still be in one thread's cache while its context is switched out and the other thread's context switches in. In that case, the thread that just took over the (single) processor will not see that the field has changed.
Since these things can happen even with one processor, they are bound to happen with more than one processor, so indeed, you need to protect your shared data.
Whether volatile
is the right choice or not depends on what type it is and what kind of change you are trying to protect from. But again, that has nothing to do with the number of processors.
If the field is a reference type, then volatile
only ensures the vilibility of new assignments to the field. It doesn't protect against changes in the object it points to - for that you need to synchronize.
Upvotes: 0
Reputation: 200206
I am assuming you are considering using volatile
vs. not using any special provisions for concurrency (such as synchronized
or AtomicReference
).
It is irrelevant whether you are running single-code or multicore: sharing data between threads is never safe without volatile
. There are many more things the runtime is allowed to do without it; basically it can pretend the accessing thread is the only thread running on the JVM. The thread can read the value once and store it on the call stack forever; a loop reading the value, but never writing it, may be transformed such that the value is read only once at the outset and never reconsidered, and so on.
So the message is simple: use volatile
—but that's not necessarily all you need to take care of in concurrent code.
Upvotes: 1