[concurrency-interest] Unsafe publication of new objectsquestion
hans.boehm at hp.com
Tue Nov 16 19:06:35 EST 2010
> From: David Holmes
> Viktor Klang writes:
> > On Tue, Nov 16, 2010 at 7:38 PM, Andrew Trick
> <andrew.trick at gmail.com> wrote:
> >> I read Joseph's question as "how does one implement a JVM that meets
> >> the JVM spec". Maybe this wasn't the best forum for that discussion?
> >> I think David answered your question to the effect that it's the
> >> programmer's responsibility to synchronize constructors in general,
> >> but final fields have some implied synchronization.
> > What I'm saying is that if there was no logic in the constructor, all
> values for all fields
> > would have to be allocated before the call, and you would be sure
> that references to the object
> > was not exposed before it was fully constructed.
> Premature exposing of 'this' in only one kind of issue that can arise.
> The broader unsafe-publication issue simply requires creation of an
> object that is assigned to a non-volatile static field. In such as case
> there is no guarantee that the stores to the object's fields will be
> visible before the store of the object reference to the static field.
> The only required safety-guarantees are that the object itself must be
> "valid" (correct header, vtable etc) and the fields must be seen to at
> least have their default-initialized valuses ie no out-of-thin-air
> values are allowed.
> What a VM has to do to meet these requirements depends on how the VM
> implements a whole bunch of things.
> David Holmes
Yes. But at the risk of repetition, it's also worth remembering that none of
these problems can occur unless you first introduce a data race. In this case, you
must store the this pointer and read it back in another thread without
proper synchronization, i.e. with nothing to prevent the store and the read
from occurring at the same time. So long as you don't do that, and there
is no untrusted code that can do it, you're fine. No data races, no problems.
More information about the Concurrency-interest