Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Better usage of try-with-resources; correct typos/wording

...

Imagine you have a servlet which dynamically generates images and serves them via the Java javax.imageio.ImageIO. To write the image to the OutputStream, perhaps you are doing something like this:

No Format
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedImage img = createMyImage(); // makes a BufferedImage
        
        response.setContentType("image/png");
        try {
            try (OutputStream out = response.getOutputStream()) { // try-with-resources
                ImageIO.write(img, "PNG", out);
            }
        } catch (IOException ex) {
            // Client abandonedaborted connection
        }
    }

Now, although there shouldn't be any Exception logged (because the IOException which occurs when the client abandoned aborted the connection is ignored), you see strange Exceptions in Tomcat's log which may belong to other Servlets/JSP (at least with Sun/Oracle JVM on Windows), saying that the response has already commited, althought you didn't write anything to it at that time. For example:

...

No Format
        response.setContentType("image/png");
        try {
            try (OutputStream out = new MyImageIOOutputStream(response.getOutputStream())) {
                ImageIO.write(img, "PNG", out);
            }
        } catch (IOException ex) {
            // Client abandonedaborted connection
        }

and the errors should be gone away.

...