I am trying to write a REST api to allow users to download large files (ie > 2GB) on Spring boot. I am hitting with "Java Heap outOfMemoryException". I tried to triage the issue, i see that HttpServetResponse object is of type : ContentCachingResponseWrapper. This class caches all content written to the output stream and when cached data size becomes around 258MB, i get OutOfMemoryException. Why at 248 MB, because JVM has 256 MB of heap memory.
The default flushBuffer() method in ContentCachingResponseWrapper is empty. If i try to call copyBodyToResponse(), which is used to copy data from cache to stream, it works fine, but it closes the stream as well. This leads to only sending first chunk of data to client.
any suggestions ?
public void myDownloader(HttpServletRequest request, HttpServletResponse response) {
//response.getClass() is: ContentCachingResponseWrapper
byte[] buffer = new byte[1048576]; // 1 MB Chunks
FileInputStream inputStream = new FileInputStream(PATH_TO_SOME_VALID_FILE);
int bytesRead= 0;
ServletOutputStream outputStream = response.getOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
outputStream.flush();
response.flushBuffer();
}
}
I get following error:
Caused by: java.lang.OutOfMemoryError: Java heap space
at org.springframework.util.FastByteArrayOutputStream.addBuffer(FastByteArrayOutputStream.java:303) ~[spring-core-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.util.FastByteArrayOutputStream.write(FastByteArrayOutputStream.java:118) ~[spring-core-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.web.util.ContentCachingResponseWrapper$ResponseServletOutputStream.write(ContentCachingResponseWrapper.java:239) ~[spring-web-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
Resource
and let Spring deal with it. Why are you handling this yourself? – Lovell