3
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
    ...
    inputStream.close(); // necessary?
}

For an API endpoint that accepts a file input, do we need to manually close the InputStream or does the framework do it for us?

I have checked the Jersey docs but could not find any information about it.

Looking for credible source or some way to validate it.

Avery235
  • 4,756
  • 12
  • 49
  • 83

3 Answers3

2

It is your responsibility to close InputStream.

Jersey intrinsically cannot know when to close your stream.

Hlib
  • 2,944
  • 6
  • 29
  • 33
  • 2
    Is it? Jersey acquired the stream so jersey should close it, at least when the http request ends. When implementing a custom MessageBodyReader the [documentation](https://jersey.github.io/documentation/latest/message-body-workers.html#d0e6838) explicitly states "Do not close the entity input stream in your MessageBodyReader implementation. The stream will be automatically closed by Jersey runtime." – sgdesmet Nov 07 '18 at 12:55
1

1) after you consumed the InputStream you can assume that it's safe to close it.

2) You can also register the InputStream with the Jersey ClosableService, according to its documentation it will close the InputStream for you. ClosableService

I hope that helps.

Toby
  • 116
  • 6
1

I just wondered the same thing and tried it out in the debugger. Jersey does not close the stream for you.

I think the most elegant way is to use try-with-resources, which can take arbitrary expressions since Java 9 and calls close() for you.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
...
try (inputStream) {
   //...
} catch (IOException e) {
   //...
}
Tommy
  • 739
  • 8
  • 24