On Sat, Apr 5, 2008 at 5:07 AM, Jerome Louvel <[EMAIL PROTECTED]> wrote:
> Thanks for the suggestion about the safe double-check idiom, very cool. As
> Request/Response have many optional property and as those are very
> frequently created objects, I think we should ready try to keep lazy
> initialization in place.
OK. At some point it would be great to do some profiling with and without
lazy init to see what effect the extra object creation has.
Uh-oh, that probably sounded like volunteering ... maybe I better retract
that comment! :-)
> However, I don't see cases where the Request/Response objects (and
> dependent
> objects) would be access by multiple threads *at the same time*, only by
> different threads at different times if we do async handling or async NIO
> writing.
>
> Could that assumption save us some additional synchronization work?
>
No. As long as there is a window in which one thread can observe the field
with a null value before another thread initializes the field, there is a
bug. It might be highly unlikely to cause trouble in practice, but that just
makes the bug harder to detect when it finally does trigger.
The complexity of the double-check lazy init idiom is daunting (to me,
anyway), but you're not obliged to use volatiles. Simple synchronization
works, too:
@GuardedBy("this") private FieldType field;
public synchronized FieldType getField() {
if (field == null)
field = initialFieldValue();
return field;
}
@GuardedBy("this") means that *all* access to the field is performed in a
synchronized (this) {} block (or a synchronized method). This might be
slightly slower than using volatile on some platform/hardware combinations,
but it's the *only* way to go if you have a class invariant that involves
multiple non-final fields. As I said, I haven't looked hard to see if that
is the case with Request, Response, etc.
--tim