Main Tutorials

Java 8 – Should we close the Stream after use?

Only Streams whose source are an IO channel like Files.lines(Path, Charset) need to be closed.

Read this Stream JavaDocs

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

1. For normal Stream like this, the stream instance does not need to be closed after use.

Java8StreamExample.java

package com.mkyong;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8StreamExample {

    public static void main(String[] args) {

        Stream<String> stream = Stream.of("A", "B", "C");

        List<String> filter = stream.filter(x -> !x.equalsIgnoreCase("B"))
			.collect(Collectors.toList());

        // no need close the stream.
        //stream.close();

        System.out.println(filter); // [A, C]

    }

}

2. For Stream whose source are an IO channel, close it with try-with-resources

Java8StreamIO.java

package com.mkyong;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8StreamIO {

    public static void main(String[] args) {

        String path = "c:\\projects\\app.log";

		// auto close
        try (Stream<String> lines = Files.lines(Paths.get(path))) {

            String content = lines.collect(Collectors.joining(System.lineSeparator()));
            
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Nick
4 years ago

Worth mentioning BaseStream’s onClose method here too. It allows you to add additional Runnables to happen “on close”. When I turned a JDBC ResultSet into a stream, that’s how I made sure that all the JDBC resources were closed when the stream was finished with.(https://github.com/nwillc/fun-jdbc)