Jeroen Brattinga wrote:
Volatile means that a thread won't cache the (value of) a variable. So
your making sure that every thread sees updates on that variable.
More precisely, defining a variable as 'volatile' will forbid the JiT compiler to optimize the code up to a point the variable is put into a registry, but remains a plain java object. This is important because a registry is *not* shared with other threads, which is potentially a problem when another thread want to modify or read this variable.
The Volatile keyword DOES NOT provide protection against multiple
read/writes from different threads!
In fact, it does. But you can only protect the concurrent access for simple get and set operations, not for any other kind of operation (like i++, for instance, if i is declared as volatile).

Synchronization, locks or atomic
variables are still needed when this is an issue.

In any case, I would suggest we don't use volatile, as it masks some semantic. Using a synchronized portion may cost slightly more time, but at least, it is explicit, and helps coders to remember what's going on with the protected variable.

For those who don't clearly understand the meaning of Volatile, and its consequences, I would suggest the perfect book "Java concurrency in practice", written by Brian Goetz, especially chapter 3.1.4.


--
--
cordialement, regards,
Emmanuel Lécharny
www.iktek.com
directory.apache.org


Reply via email to