[concurrency-interest] Volatile happens before question
khilan at doc.ic.ac.uk
Wed Jan 18 08:05:30 EST 2012
I may have misunderstood the intentions here but according to the JCIP
book, if you have a single field in a thread-shared class then it's
recommended to use AtomicX types for that field rather than having a
separate lock field to protect it.
What you appear to be doing is versioning. When you perform a set, you
increase the current version and when you get, you check that the
version hasn't changed. I thought that writes to a volatile always
happened-before a read, so if the version number was updated you would
definitely see it. Hence, if set was called between the two calls to
counter.get(), you would get different values and then loop.
With regards to reordering, in JCIP 3.1.4, it says:
"When a field is declared volatile, the compiler and runtime are put
on notice that this variable are shared and that operations on it
should not be reordered with other memory operations. Given that
counter.get() reads a volatile value, this ensures that operations are
not reordered with these calls? Or am I misunderstanding something?
Department of Computing
Imperial College London
On 18 January 2012 12:20, Zhong Yu <zhong.j.yu at gmail.com> wrote:
> On Tue, Jan 17, 2012 at 5:13 PM, Boehm, Hans <hans.boehm at hp.com> wrote:
>> Another way to look at this is that compiler reordering that is only observable by programs with data races is generally allowed. The program below clearly has an inherent data race on b. If you make b volatile, the data race, and the problem, go away.
> Not by the definitions in the book.
> Volatile r/w can form a data race, if there is neither hb(r,w) nor
> hb(w,r), which is possible when r is before w in synchronization
> P.S. Reading JLS, the wording of "allowed to observe" (17.4.5) is
> very misleading; it is defined only in term of happens-before order,
> meaning a volatile read can be "allowed to observe" a later volatile
> Zhong Yu
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
More information about the Concurrency-interest