在org.apache.catalina.connector.CoyoteWriter.flush()中导致此NPE的原因是什么?

时间:2017-06-09 17:11:16

标签: java tomcat

 private void respond(String response) {

    httpServletResponse.setContentType("application/json");
    httpServletResponse.setCharacterEncoding("UTF-8");

    try {
        PrintWriter out = httpServletResponse.getWriter();

        out.print(response);
        out.flush();

    } catch (IOException ex) {
        log.error("Error while writing response",ex);
    }

}

此代码在out.flush()处抛出空指针。 httpServletResponse是实例变量。我已经确认响应不为空。从Apache的aync http客户端lib的CloseableHttpAsyncClient.execute.completed()内部调用此函数。

LOG:

Caused by: java.lang.NullPointerException: null
    at org.apache.coyote.http11.InternalNioOutputBuffer.flushBuffer(InternalNioOutputBuffer.java:234) ~[tomcat-coyote.jar:8.0.14]
    at org.apache.coyote.http11.InternalNioOutputBuffer.addToBB(InternalNioOutputBuffer.java:189) ~[tomcat-coyote.jar:8.0.14]
    at org.apache.coyote.http11.InternalNioOutputBuffer.commit(InternalNioOutputBuffer.java:177) ~[tomcat-coyote.jar:8.0.14]
    at org.apache.coyote.http11.AbstractHttp11Processor.action(AbstractHttp11Processor.java:739) ~[tomcat-coyote.jar:8.0.14]
    at org.apache.coyote.Response.action(Response.java:179) ~[tomcat-coyote.jar:8.0.14]
    at org.apache.coyote.Response.sendHeaders(Response.java:341) ~[tomcat-coyote.jar:8.0.14]
    at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:331) ~[catalina.jar:8.0.14]
    at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:313) ~[catalina.jar:8.0.14]
    at org.apache.catalina.connector.CoyoteWriter.flush(CoyoteWriter.java:98) ~[catalina.jar:8.0.14]
    at com.thruport.aje.rotator.reward.async.RewardRequest.respond(RewardRequest.java:185) ~[output/:na]
    at com.thruport.aje.rotator.reward.async.RewardRequest.lambda$new$2(RewardRequest.java:131) ~[output/:na]
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602) ~[na:1.8.0_121]
    ... 8 common frames omitted

1 个答案:

答案 0 :(得分:0)

事实证明我不应该在这里刷新,因为Servlet容器将在Servlet生命周期结束时处理它,并且Buffer在此阶段不会准备好进行刷新。这个 Nullpointer exception while flushing ServletOutputStream和此 Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?答案有帮助。