Johny19 Johny19 - 5 months ago 11
Java Question

Java Try-with-resource storing input stream in Map

In my API(Spring boot) I have an endpoint where users can upload multiple file at once. The endpoint takes as input a list of MultiPartFile

I wish not to directly pass this Multipartfile object to the service directly so I loop through each MultipartFile and create a simple map that stored the fileName and its InputStream

Like this:

for (MultipartFile file : files) {
try (InputStream is = multipartFile.getInputStream()) {
filesMap.put(file.getOriginalFilename(), is);
}
}
service.uploadFiles(filesMap)


My understanding for Java streams and streams closing is quite limited.
I thought that try-with-resource automatically closes the inputStream once the code reached the end of the try block.

In the above code when does exactly the the multipartFile.getInputStream() gets closed?
The fact that I'm storing the stream in a map will that cause a memory leak?

Answer

Stream closes right after execution reaches closing bracket of try block. It is okay to store InputStream anywhere after you closed it. But be aware of that you can't read anything from this stream after you closes it.

Thanks to comments

Also, be aware of that some streams have special behavior on close() and it always depends on Stream realization. For example:

  • If you try to read from closed FileInputStream you will get java.io.IOException: Stream Closed
  • If you try to read from closed ByteArrayInputStream it will be okay, because of it's special close() realization: public void close() throws IOException {}
Comments