stream.spliterator()
是否隐式关闭了stream
,或者需要在之后明确关闭它?stream.spliterator()是否关闭流?
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?
乍一看,似乎.spliterator()
方法关闭stream
,但没有叫stream.close()
。至少如果我在调用.spliterator()
方法后马上关闭它,似乎不会影响分割器的操作。
Stream<String> stream = Stream.of("a", "b", "c").limit(2);
Spliterator<T> spliterator = stream.spliterator();
stream.close();
// Some low lever operation with the spliterator
这个问题可以被扩展到其它stream
方法,例如,该.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?
原因这个问题是有深刻的清晰度当stream
需要明确地关闭,在我并不需要明确地关闭它的情况下,当onClose()
定义的动作将发生?
Stream接口扩展了AutoCloseable接口,所以我在guest垃圾收集器处理流时会调用'onClose'动作。但最好尽快关闭它。 – Tet
不,没有垃圾收集器驱动关闭流 - 如果流有这样一个终结器,结果将是灾难性的。底层资源本身*可能*具有自动清理,但取决于资源。但这并不意味着执行任何注册到流中的关闭处理程序。 – Holger
只是为了增加细节,这里是一个很好的洞察流和[TWR斯图尔特](https://stackoverflow.com/a/22929990/1746118) – nullpointer