users@servlet-spec.java.net

[servlet-spec users] Re: Getting a RequestDispatcher from an async thread

From: Greg Wilkins <gregw_at_intalio.com>
Date: Wed, 30 May 2012 12:15:50 +0200

Rossen,

the reason why jetty returns null, is that getRequestDispatcher is a
method that is relative to the current context that is handling the
request and this is only known inside the scope of a call to a
context.

Consider a request that is dispatched from ContextA to ContextB and
that while in the a servlet inside ContextB, async is started and the
method returns.

While still in the ContextB servlet, a call to
request.getRequestDispatcher should be possible and should return
results relative to ContextB
but when returned from the dispatch to ContextB we are back in a
filter/servlet in ContextA, then a call to getRequestDispatcher should
be returned relative to ContextA

But if we let an async thread call getRequestDispatcher after async is
started, then we have a race condition. Depending on the timing of
the call, the method will return a result relative to ContextB, then
ContextA and then undefined. Even if we define which context it
should be relative to, then the value will still be changing and we
still have a race condition. This get's even more confusing as we can
have a request that has been dispatched to ContextC by an async
thread, so then before the dispatch is actually done, should the
method be relative to the suspending Context or the destination
context?

Any request method that is dependent on context (even getSession)
should not be called from an async thread because the context of a
request is a volatile attribute of the request. Some containers may
return values, and they may even be correct for most situations, but
they are intrinsically not safe.

cheers