javajava-8java-streamspliterator

Does the stream.spliterator() close the stream?


Does the stream.spliterator() implicitly closes the stream, or there is a need to explicitly close it afterwards?

Stream<String> stream = Stream.of("a", "b", "c");
Spliterator<T> spliterator = stream.spliterator();
// Some low lever operation with the spliterator
stream.close(); // do we need to close?

At first glance, it seems that the .spliterator() method closes the stream, but without calling stream.close(). At least if I close it straight away after the .spliterator() method is invoked, it seems not affection the spliterator operations.

Stream<String> stream = Stream.of("a", "b", "c").limit(2);
Spliterator<T> spliterator = stream.spliterator();
stream.close();
// Some low lever operation with the spliterator

This question can be extended to other stream methods, for example, the .findAny().

stream.findAny() // Can I assume that I don't need to close the stream?
stream.onClose(() -> System.out.println("hi!")).findAny()`
// when the `onClose()` action will be called?

The reason for that question is to have deep clarity when a stream needs explicitly to be closed, and in the cases where I don't need to explicitly close it, when the onClose() defined actions will take place?


Solution

  • Terminal operations never close the stream. Closing has to be done manually. The only place where automatic closing happens is within the flatMap operation, where manual closing of the substreams usually created on-the-fly would be somewhere between hard and impossible.

    This also applies to the Stream.spliterator() method. In your examples, it makes no difference because the streams created via Stream.of(…) do not need to be closed and have no onClose() operation registered by default.

    You have to consult the documentation of the factory methods to find out when a stream need to be closed. E.g. like Files#lines(Path, Charset).

    See also Does collect operation on Stream close the stream and underlying resources? or Does Java 8 Stream.iterator() auto-close the stream when it's done?