[concurrency-interest] synchronized on construction

Jeremy Manson jmanson at cs.purdue.edu
Wed May 24 15:48:54 EDT 2006

Thomas Hawtin wrote:
> Jeremy Manson wrote:
>> The system will not move the racy write up before the lock is acquired, 
>> although it may move it inside the synchronization block.  We have 
>> "Roach Motel Semantics" - you can move the write up into the 
>> synchronization block, but you can't move it out of that block.
>> The reason for this has to do with locking and happens-before, and I 
>> shall leave it as an exercise to the reader ;) .
> So, in this situation, as a reader...
> Suppose we have thread t that creates an object with a synchronised 
> block in the constructor and thread u that uses that object under 
> synchronisation.
> Suppose further, for the sake of contradiction, that the lock in u 
> occurs earlier in the synchronisation order than t. The read of the 
> object reference in u must happen-before it uses the lock. The use of 
> the lock in t must happen-before the write of the object reference. 
> Therefore the read of the reference in u must happen-before the write of 
> the reference in t, so will have an old value.
> Is that vaguely right?

It is along the right lines.  The best way to think about it is to 
consider two, more generic locking regions:

Thread 1:
synchronized (o) {
   r1 = x;
   r2 = y;

Thread 2:
synchronized (o) {
   y = 1;
x = 1;

Let's say that Thread 1's synchronized block happens-before Thread 2's. 
  Then both reads in Thread 1 are guaranteed to see the value 0 (because 
the reads happen-before the write in Thread 2).

If you move the write to x _inside_ the locking region, the read will 
still not see the value 1, because the read of x will still 
happen-before the write to x.

However, if you move the write to x to _before_ the locking region, then 
the read of x might see the value 1.  Since the read of x happens-before 
the write to x, the system can't do this.

>> If you don't have that synchronization in your code, then there you have 
>> a bug.  A data race.  Data races rot the brain and corrupt the soul.
> Yeah but my soul is already corrupt and my brain nicely folded.

... and I'm sure your clients appreciate when that comes out in your code!


More information about the Concurrency-interest mailing list