[concurrency-interest] Synchronization question

Holger Hoffstätte holger at wizards.de
Wed Jun 28 09:16:28 EDT 2006

Dhanji R. Prasanna wrote:
> On 6/28/06, Holger Hoffstätte <holger at wizards.de> wrote:
>> Brian Goetz wrote:
>> > And, just for completeness: synchronized write + nonsynchronized read
>> > doesn't create the required happens-before, so it doesn't work.  The
>> > getter in such a case isn't required to ever return anything other than
>> > the default (zero) value.
>> This made me curious. While "strictly speaking" the above behaviour might
>> be correct according to the spec/revised memory model, in practice (as in
>> stuff I can buy/run today) the unsynchronized read *will* succeed - maybe
> I believe with regard to the original question, the unsynchronized
> read is not expected to be deterministic because there isnt a
> happens-before edge forcing the 2 threads into a write/read sequence.

The original poster assured that the setting (== exit of the synchronized
method body) was guaranteed to happen before the read. I don't think
anybody would expect the read to return a non-null value even though no
value has ever been set yet. Not even Futures can do that. ;)

> Im not sure what you mean by "succeed", but for the required behavior
> (i.e. write prior to read) one cannot guarantee that a synchronized
> write + unsynchronized read will suffice.

I'm mainly interested in unambiguous clarification of the apparently (?)
possible time window that may or may not exist after the synchronized set
method has returned. The size of that window (if it exists?) constitutes a
"visibility race" and if it is ever allowed to be "forever" - as per
Brian's comment above - then many applications will produce "interesting"

> Declaring the variable as volatile forces both threads to deal with
> the same memory but still does not solve the issue of sequencing the
> write/read. This is how I read Brian's and the others' responses.

Brian qouted: "Storing a reference to [the published object] into a field
that is properly guarded by a lock." but then added "all accesses (read
and write)". The former would allow for an unspecified window where the
change is not-quite-visible-yet, but eventually will (MEM_AUTO_COMMIT :).
The latter would mean that *all* references to *all* fields of a compound
object that is shared between threads *must* be accessed from inside a
synchronized method or at least in a synchronized block to ensure
visibility. We can only guess how many lines of Java code don't do that;
that's why I was wondering about the possible fallout.

Sorry if I'm being dense or overly picky here - if I'm missing something
fundamental please set me straight. All this should be put into a FAQ that
every random Java dude can understand!


More information about the Concurrency-interest mailing list