Created
May 21, 2014 16:42
-
-
Save rajeevprasanna/04b4c9322a5245877c1f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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