[concurrency-interest] synchronized on construction

Thomas Hawtin tackline at tackline.plus.com
Wed May 24 15:29:28 EDT 2006


Jeremy Manson wrote:
> Thomas Hawtin wrote:
>> Under the new JMM would a synchronised block in the constructor 
>> guarantee to fix the problem? Does the racy write of the Vector 
>> reference, outside of the synchronised block, necessarily come after 
>> the block itself. Could it technically be moved up before the lock is 
>> acquired? Or am I misinterpreting something?
>>
> 
> 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?

> 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.

> This bug discusses making the seed final, which ends up being a separate 
> issue from the one in your first paragraph.  Declaring a field final 
> means that the correctly constructed value will be visible to threads 
> that see a reference to that object, even if you have no additional 
> synchronization.  It is an excellent way to provide thread-safe 
> initialization, as long as your field doesn't change.  This cannot be 
> done for the fields of Vector, though, because its fields can be changed.

It wasn't the reference I was worried about, but the resetting of the 
seed after the final field is assigned. Even ignoring the above, it's 
still fine because the freeze happens at the end of the constructor, not 
at the assignment.

Tom Hawtin


More information about the Concurrency-interest mailing list