Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created May 21, 2014 16:42
Show Gist options
  • Save rajeevprasanna/04b4c9322a5245877c1f to your computer and use it in GitHub Desktop.
Save rajeevprasanna/04b4c9322a5245877c1f to your computer and use it in GitHub Desktop.
Especially critical is high temporary memory usage in enterprise applications, which can have a high number of concurrent users. Because it can happen out of the blue, this OutOfMemoryError is especially troublesome, as it cannot be countered with a nightly reboot. The following code illustrates the problem:
byte[] image = getTheByteImage();
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
out.write(image);
out.flush();
out.close();
While it is not that obvious, the code consumes memory on heap for each image before sending it to the browser. A much better variant would be to stream the image like this:
InputStream image = getTheImageAsStream();
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(image, out);
out.flush();
out.close();
(Of course BufferedStreams and IOUtils use byte[] internally as well, but this is much smaller)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment