[concurrency-interest] Double Checked Locking in OpenJDK

Chris Povirk cpovirk at google.com
Wed Aug 15 22:03:19 EDT 2012


>> > local = new Vector();
>> > synchronized (local) {}
>> > shared = local;
>>
>> construction happens before synchronized block
>> synchronized block happens before write
>> (=> construction happens before write)
>
> Nope. construction happens-before end of synchronized block. write also happens-before end of synchronized block. roach-motel rules allow everything to be moved into the sync block.

True, I am being imprecise in treating the synchronized block as a
single action.
> Again use of object could be moved inside the sync-block. But sync-block here can not be entered until after other thread releases the lock. So that establishes the happens-before ordering:
>
> everything in writer thread happens-before release of lock
> release of lock happens-before acquire of lock in second thread
> acquire of lock happens-before use of object
> => everything in writer thread happens-before use of object

I'm on board with this except for one part, which is apparently the
part where my thinking is too confusing for you to help me :)

"But sync-block here can not be entered until after other thread
releases the lock."

I agree that the threads can't be in the synchronized block at the
same time.  What I don't understand is what prevents the reader thread
from entering its block before the writer thread enters its block.
You give an explanation here:

> The above paragraph is confusing to me. The reader thread won't attempt to execute its sync block unless it sees the write to shared. The write to shared happens after the writer thread acquires the lock (and maybe after it releases it). So the reader will only attempt to acquire the lock once the writes have progressed to the point where shared was written, but it can't actually acquire the lock until all the writes are completed.

But does the mere fact that the reader thread sees the write to shared
establish a happens-before relationship between the read and the
write?  Surely it can't, or else it would be safe to publish the
object with no synchronized blocks at all... I think...?



More information about the Concurrency-interest mailing list