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???

Darshan Patel
  • 2,839
  • 2
  • 25
  • 38

2 Answers2

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()?

Community
  • 1
  • 1
skaffman
  • 398,947
  • 96
  • 818
  • 769
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);
    }
Pavel Niedoba
  • 1,554
  • 2
  • 19
  • 36