Hi, On Wed, Jul 9, 2014 at 1:18 AM, Marko Asplund <marko.aspl...@gmail.com> wrote:
> Hi, > > I'm just starting out with using the Servlet 3.1 asynchronous processing > API. > I use the API for generating response content, that can potentially be a > slow process, in another thread. > The code appears to be working, but since the specification contains many caveats, I'd like to try and verify correctness. > > There's a couple of parts in particular that I'm wondering about: > - what's the correct way to deliver error response to client? Can I just > cast the response acquired from AsyncContext to HttpServletResponse and use > the normal Servlet API mechanisms? > - does the code contain thread-safety issues in particular related to the > response object and OutputStream? > > Here's a simplified version of my code: > > @Override > protected void doGet(HttpServletRequest req, HttpServletResponse resp) > throws ServletException, IOException { > final AsyncContext asyncContext = req.startAsync(); > asyncContext.start(new Runnable() { > @Override > public void run() { > HttpServletResponse response = null; > try { > response = (HttpServletResponse)asyncContext; > Maybe it is implementation detail that this cast works but usually you have to use http://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#getResponse() to get the response > if(hasOperationFailed()) { > > response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); > } else { > > response.getOutputStream().write(generateResponseContent().getBytes()); > } > } catch (IOException e) { > try { > > response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); > } catch (IOException e1) { > e1.printStackTrace(); > } > } > asyncContext.complete(); > } > }); > } > > Any feedback and pointers would be welcome. > > > marko >