Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!gegeweb.org!aioe.org!.POSTED!not-for-mail From: Steven Simpson Newsgroups: comp.lang.java.programmer Subject: Re: Volatile happens before question Date: Wed, 18 Jan 2012 11:22:23 +0000 Organization: Aioe.org NNTP Server Lines: 62 Message-ID: References: <09848313-2372-4c23-8f52-fa84c612c100@u32g2000yqe.googlegroups.com> <1pi7kea3zdo0b.1ixhuq3p9ybbu$.dlg@40tude.net> NNTP-Posting-Host: zZEYLmC40wfQ+6WXR+XDEA.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:8.0) Gecko/20111124 Thunderbird/8.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:11457 On 18/01/12 07:47, Peter Duniho wrote: > Because the memory model doesn't stipulate what must happen, compilers and > run-times are permitted to allow the write to "b" to be reordered to occur > before the write to "a". This reordering then can cause the early-written > value of "1" to be observed in thread #2, even as it just one program > statement later observes the still-unwritten variable "a", seeing a value > of "false". Let's see if I've followed this... In the first case, thread 1 writes 'b', then volatile-writes 'a'. Thread 2 volatile-reads 'a', then reads 'b'. We only care when the read of 'a' happens after the write of 'a', as otherwise we don't use the value of 'b': 0 1 2 3 4 5 | | V V --------------------------------1 b a * * a b --------------------------------2 | | V V 'volatile' guarantees that the write to 'b' at time 1 is not optimized in any way to happen after t2. If it were not guaranteed, it might happen after t4, which we assert won't happen. So, 'volatile' prevents the write to 'b' from jumping into the future of the write to 'a'. In the second case, thread 1 volatile-writes 'a' (as true), then writes 'b'. Thread 2 reads 'b', then volatile-reads 'a'. Thread 2 copies 'b', but only uses the copied value if 'a' is later found to be (still) false, so we only care when the read of 'a' happens before the write of 'a': 0 1 2 3 4 5 | | V V --------------------------------1 a b * * b a --------------------------------2 | | V V This time, 'volatile' does not guarantee anything for the write to 'b'. It could be optimized to happen as early as t0, so we cannot assert that thread 2 will always use the initial value of 'b'. So, 'volatile' does not prevent the write to 'b' from jumping back into the past of the write to 'a'. -- ss at comp dot lancs dot ac dot uk