Close

Java 8 Streams - Stream.close Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.BaseStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamLogicBig

Method:

void close()

Closes this stream, causing all close handlers for this stream pipeline to be called.

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.)

Examples


package com.logicbig.example.stream;

import java.util.stream.Stream;

public class CloseExample {

public static void main(String... args) {
Stream<String> stream = Stream.of("one", "two", "three", "four");
stream.forEach(System.out::println);
//it's not necessary
stream.close();
}
}

Output

one
two
three
four




We cannot use the stream if it's closed already.

package com.logicbig.example.stream;

import java.util.stream.Stream;

public class CloseExample2 {

public static void main(String... args) {
Stream<String> stream = Stream.of("one", "two", "three", "four");
stream.close();
stream.forEach(System.out::println);
}
}

Output

Caused by: java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.sourceStageSpliterator(AbstractPipeline.java:279)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at com.logicbig.example.stream.CloseExample2.main(CloseExample2.java:16)
... 6 more




See Also