> Is it such a black-and-white scenario? I would have thought there were a few
> caveats with which publishing 'this' in the constructor is safe. So within
> either object's constructor the following should hold:
>
> - foo = new Foo(this) is called last, after the state of the object has been
> setup
> - Foo does not publish Bar
> - Foo does not mutate Bar
> - Bar does not publish Foo within the constructor
>
> I've not read the reference you gave though, so I expect I'm missing
> something, but I'd be surprised if there were no conditions under which
> passing 'this' into a composed object in the constructor is unsafe.

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