RE: JavaMemoryModel: Idiom for safe, unsynchronized reads

From: David Holmes (dholmes@ics.mq.edu.au)
Date: Tue Jun 29 1999 - 00:48:49 EDT


> P.S. In a multi-threaded environment, the above code can also lead
> multiple executions of the "new" expression, probably not what the
> programmer intended. Thus, the recommended pattern for such a method
> is:
>
> String getFoo() { // Version A
> if (foo == null) {
> synchronized (this) {
> if (foo == null)
> foo = new String(..whatever..);
> }
> }
> return foo;
> }

This "recommended pattern" is not a guaranteed correct coding idiom on a
multi-processor under any language, including Java under the current
definition of the memory model. It is not equivalent to the synchronized
version of getFoo() because the reader, that is the thread that finds foo
to be non-null, does not perform synchronisation thus leading to memory
consistency problems. These problems allow a reader to see a String object
that may not be completely constructed.

> In general, it seems hard to believe that people find
> the religion of "synchronize all accesses to shared variables" as
> difficult.

It is not that the religion is difficult - I believe in the religion. The
issue is that not adhering to the religious dogma should not cause
universal invariants to fail. Failure to properly synchronise access to
shared variables should allow application invariants to fail not language
ones. Thus when you read a shared variable you should always see a value
that was written by some thread - not arbitrary garbage, nor transient
"default" values.

> Version (B) is simpler to understand than Version (A). Version (A)
> is preferable because it's faster.

Versions A and B are not equivalent.

David

-------------------------------
This is the JavaMemoryModel mailing list, managed by Majordomo 1.94.4.

To send a message to the list, email JavaMemoryModel@cs.umd.edu
To send a request to the list, email majordomo@cs.umd.edu and put
your request in the body of the message (use the request "help" for help).
For more information, visit http://www.cs.umd.edu/~pugh/java/memoryModel



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