[concurrency-interest] Parametric Initialization On Demand Holder Idiom ?
dcholmes at optusnet.com.au
Fri Aug 31 03:11:44 EDT 2007
> Agree. However, is it possible to contrive an example where a
> thread-safe (but not super-safe like immutable) value passed to the
> SomethingMore.getInstance(params) would cause a
> surprising/unexpected/corrupted/partially-initialized result ?
I think the general answer is yes. If thread-1 sets valueHolder and thread-2
does LazySomethingMoreHolder.something (because concurrent calls to
getInstance are interleaved) and then thread-2 uses the object created by
thread-1, then it is using an unsafely published object. There is no
happens-before relationship between the construction of the object by
thread-1 and its use in thread-2.
Now Joe has pointed out the rule for final fields, but I don't think that
quite applies to this situation - or if it does then there is a problem for
The final-field rule allows you to unsafely publish an object but have final
fields of that object safely visible and "the objects to which they refer".
But I believe the intent there was to cover the case where the thread
setting the final field *also* constructed the object. That is not the case
Suppose the final-field rule does apply, then when thread-1 does:
Foo f = new Foo();
SomethingMore.valueHolder = f;
the VM has to know that valueHolder will soon be assigned to a final field
in another thread, and force a happens-before ordering between the two
actions. But the VM can't know that will happen so it won't do anything to
enforce happens before.
Of course, depending on the nature of the object itself it might be harmless
to unsafely publish it.
That's my take anyway - perhaps we need to discuss this on the JMM mailing
More information about the Concurrency-interest