Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: markspace <-@.> Newsgroups: comp.lang.java.programmer Subject: Re: Volatile happens before question Date: Tue, 17 Jan 2012 08:50:22 -0800 Organization: A noiseless patient Spider Lines: 59 Message-ID: References: <09848313-2372-4c23-8f52-fa84c612c100@u32g2000yqe.googlegroups.com> <1e7b4r38kmn2f$.1kwqeem7f8lxb.dlg@40tude.net> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 17 Jan 2012 16:50:25 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="XjIWM99mD7Ijfdu600oVPA"; logging-data="3927"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+umdJ2umEHZbps3SzosXEwbIi0tesDCB8=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20111105 Thunderbird/8.0 In-Reply-To: <1e7b4r38kmn2f$.1kwqeem7f8lxb.dlg@40tude.net> Cancel-Lock: sha1:IlaRm1cbtVDGrS27tOv5YZosU18= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:11406 On 1/17/2012 8:17 AM, Peter Duniho wrote: >> int b = 0; >> volatile boolean a = false; >> ... >> ... >> a = true; >> b = 1; >> (set a = true) happens before (set b = 1) > > It's this last assertion that fails. I believe the original assertion is true, but in code he was assuming the converse. (*) That is a is true before b is 1, but just because a is true doesn't mean that b has been set to 1 yet. There is a physical time gap in between those events. (**) In other words, the JLS does not say that: a is true iff b is 1. (iff = "if and only if"). The JLS does say: If b is 1, then a has also been set to true. (a happens before b.) The JLS does not say: If a is true, then b has been also set to 1. That last statement could be false and there could still be a valid happens-before relationship between write(a<-true) and write(b<-1). There is a time gap between a being written and b being written where you could see a==true but b==0. As a general rule of thumb, you always read the volatile FIRST and write the volatile LAST. Here in the 2nd example, a was read first and the volatile (b) was read after, so that's why it didn't work. (*) I'm wondering if the proper word is reflexive rather than converse. That is, just because (b=1) therefore (a=true) is true, does not mean (a=true) therefore (b=1) is true (it's not). Any help here? (**) These are terrible variable names for discussion a problem in English. "a" looks like the article a and b is just as bad. Use something longer and more obvious next time. I can scarcely follow my own writing, sheesh.