Is there any resource leak if I use streaming with BufferedReader in Java

Viewed 53

This is pretty much code I have. (no read or close calls). Do I need to close either InputStream or BufferedReader? is there any code smell/ resource leak here?

InputStream stream = response.getEntity().getContent();
String response = new BufferedReader(new InputStreamReader(stream)).lines()
                .collect(Collectors.joining("\n"));

EDIT

based on answer, is this correct

InputStream stream = response.getEntity().getContent();
String response;
try (BufferedReader br = new BufferedReader(new InputStreamReader(responseStream))) {
                    response = br.lines().collect(Collectors.joining("\n"));
                }
1 Answers

No, the stream is not auto closed on performing the stream pipeline operation in such cases and in fact as stated in the documentation there are also no guarantees that the reader will be at a specific position from which to read the next character or line.

In short Streams () are not responsible for manipulating the stream () that has been passed on for processing as a resource. Hence the preferred way to ensure auto-closable streams in such a case would be using try-with-resource approach as follows :

try (InputStream stream = request.getEntity().getContent();
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream))) {
    String response = bufferedReader.lines().collect(Collectors.joining("\n"));
}
Related