we will answer the question if we need to close the Java 8 Stream after use. So let’s see the case when we should close the Stream and when we don’t have to through some straightforward examples.
Today’s post will be a short one to answer the question if we need to close the Java 8 Stream after use. So let’s see the case when we should close the Stream and when we don’t have to through some straightforward examples.
What JavaDocs Says About That?
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.)
For more understanding of the Java 8 Stream, you can reach their Java Docs website.
When You Should Close the Java 8 Stream
If you are using a Stream that accepts an IO channel as a source, close it with try-with-resources as the following example.
package com.ninjadevcorner;
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 Java8StreamFileTransformer {
public static void main(String[] args) {
String pathFile = "d:\\files\\error-exceptions.log";
// auto close with the try-with-resources
try (Stream lines = Files.lines(Paths.get(pathFile))) {
String limitedContent = lines.limit(50L).collect(Collectors.joining(System.lineSeparator()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
When You Don’t Need to Close the Java 8 Stream
If you use a normal Stream like this example, you don’t have to close the Stream after using it.
package com.ninjadevcorner;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8NormalStream {
public static void main(String[] args) {
Stream stream = Stream.of(40, 100, 90, 50, 30, 19, 40);
List filter = stream.distinct()
.filter(x -> x > 30)
.collect(Collectors.toList());
// there is no need close the stream.
//stream.close();
System.out.println(filter); // [40,100,90,50]
}
}