Having had a look at JCIP I think this is one of the cases where it is 
possible to break the rule and still be safe, but as you say the potential 
for hard-to-trace errors means you'd probably want to avoid it.

Thanks Patrick.

~ Graham

> It would be best to read Java Concurrency in Practice for a full
> response. I think the answer is: there is risk involved if you publish
> "this" from within the constructor, namely that (as far as I
> understand it), the Java Memory Model will not guarantee that the
> fields of the object are all set before the constructor ends, so the
> receiver of "this" can observe a partially-constructed object. The
> problem then is that, even if the risk were small, the potential
> errors that could arise would be so confusing, and so hard to debug or
> reproduce, that it's not worth the risk.
>
> They specifically say that making the call the last call in the
> constructor won't help; I believe this is because the operations can
> be reordered.
>
> It may be possible to get around this by forcing a flush using a
> volatile or some kind of fence, but that could also be expensive if
> the class if otherwise thread-bound and you are creating new instances
> in a tight loop.
>
> I'm no expert in this area, this is just one "best practice" I've
> picked up along the way.
>
> Regards
> Patrick

--

You received this message because you are subscribed to the Google Groups "The 
Java Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/javaposse?hl=en.


Reply via email to