Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.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: Wed, 18 Jan 2012 11:59:39 -0800 Organization: A noiseless patient Spider Lines: 36 Message-ID: References: <09848313-2372-4c23-8f52-fa84c612c100@u32g2000yqe.googlegroups.com> <1pi7kea3zdo0b.1ixhuq3p9ybbu$.dlg@40tude.net> <60dddbf9-3686-4824-a918-64a59faba177@a8g2000vba.googlegroups.com> <726da9ce-57f4-4136-b50b-56a032aca196@f1g2000yqi.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 18 Jan 2012 19:59:42 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="XjIWM99mD7Ijfdu600oVPA"; logging-data="28831"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+QP2lgXvOwZfvWHD4V8WqirUvGM7cdQTs=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20111105 Thunderbird/8.0 In-Reply-To: <726da9ce-57f4-4136-b50b-56a032aca196@f1g2000yqi.googlegroups.com> Cancel-Lock: sha1:jam+zqrDVoZswV5iYDtCNuF+LX0= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:11474 On 1/18/2012 11:15 AM, raphfrk@gmail.com wrote: > On Jan 18, 6:12 pm, markspace<-@.> wrote: >> Yeah, it's a trick. > > You mean yeah, it has the same problem, so won't work either? Looking at his code a bit more carefully, I think it has problems, but not the same one. I guess the extra variables in his code that you're looking at are local variables. So those are safe, they don't figure into multi-threading concerns. The bit that confuses me is that he "protects" his map with a write counter: writeCounter.getAndIncrement(); map.put(key, value); writeCounter.getAndIncrement(); And then allows the reader(s) into the critical section whenever the writeCounter is even (why not just decrement the counter after a write access?). while (((save = writeCounter.get()) & 1) == 1); value = map.get(key); So if a reader starts "first" and passes the first test (writeCounter==0), and then starts to access the map, and then a writer comes in and also begins to access the map... yeah you have two threads accessing the map at the same time. This doesn't seem to work at all. (Hint: ConcurrentHashMap )