1

Here is the exception which I get some times while flushing ServletOutputStream. It does not occur on every request so I am not able to reproduce it.

java.lang.NullPointerException
    at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215)
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
    at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:119)
    at org.apache.coyote.http11.AbstractHttp11Processor.action(AbstractHttp11Processor.java:805)
    at org.apache.coyote.Response.action(Response.java:174)
    at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:366)
    at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:333)
    at org.apache.catalina.connector.CoyoteOutputStream.flush(CoyoteOutputStream.java:101)
    at darshan.HttpRequestHandler.returnResponse(HttpRequester.java:117)

HttpRequester.java :

private void returnResponse(HttpServletResponse response , String responseStr)
{
    InputStream in = null;
    ServletOutputStream out = null;
    try
    {
        in = new ByteArrayInputStream(responseStr.getBytes("UTF-8"));
        response.setContentLength(responseStr.length());
        out = response.getOutputStream();

        byte[] outputByte = new byte[4096];
        while(in.read(outputByte, 0, 4096) != -1)
        {
            out.write(outputByte, 0, 4096);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            in.close();
            out.flush();  //<-- Exception at this line
            out.close();
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}

Any solution for this error???

1
  • I think that stream is flushed on close. Did you try to remove the flush(); Does the NPE comes from close() then? Feb 21, 2015 at 9:43

2 Answers 2

5

Your code doesn't need to call flush or close on the input or output streams. The servlet container will take care of flushing and closing for you.

There are sometimes corner-cases where a manual flush call is required, but this isn't one of them. Calling close on either of them, however, is really not a good idea, and may be triggering a bad state within tomcat that's causing your exception.

See Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?

0

Here you probably write behind content length in last block, because it might read less than 4096bytes

byte[] outputByte = new byte[4096];
    while(in.read(outputByte, 0, 4096) != -1)
    {
        out.write(outputByte, 0, 4096);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.