Re: JavaMemoryModel: Unsynchronized read as an optimization

From: Robert Munyer (munyer@digi-net.com)
Date: Mon Dec 18 2000 - 23:18:01 EST


On 12/18/00, David Holmes <dholmes@dstc.edu.au> wrote:

>> No, there's a big difference. In your code above, it's possible
>> for the write of the variable "helper" to arrive at the main memory
>> before all of the writes performed by the constructor have arrived.
>
> In that case can't you have three flag values:
> - must use sync
> - can use unsync if writes are not reordered
> - can use unsync always
> ?

Yes that's correct. I didn't make any attempt to distinguish between the
second and third cases, because the difference in cost is very slight. If
getHelper is called N times, the idiom I suggested can save up to N-2 synch
operations. Treating the third case differently could only save one more.

>> I think you're describing something that can't happen. Neither of the
>> two Booleans in my code ever changes from "true" to "false." A thread
>> can see a stale "false" value, but a stale "true" value is impossible.
>> The new memory model won't drop the "not out of thin air" rule, will it?
>
> My understanding, and I'm sure Bill or Doug or someone, will correct me if I
> am wrong, is that a variable accessed without synchronization, that is not
> volatile, or accessed via a volatile or final ref, is allowed to take on any
> value including garbage. The main example here is, as before, reading a
> value that happens to be cached, but where the cached value does not
> represent a value ever written to that variable.

That would definitely kill my code, because it makes use of the "not out of
thin air" rule. I'll paste the rule here so no one will have to look it up:

    When a thread uses the value of a variable, the value it obtains is in
    fact a value stored into the variable by that thread or by some other
    thread. This is true even if the program does not contain code for
    proper synchronization. For example, if two threads store references
    to different objects into the same reference value, the variable will
    subsequently contain a reference to one object or the other, not a
    reference to some other object or a corrupted reference value. (There
    is a special exception for long and double values; see §17.4.)

-- Robert Munyer <munyer@digi-net.com>

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:29 EDT