简体   繁体   English

在异常情况下关闭由 flatMap 打开的 Java 8 流?

[英]Closing a Java 8 stream opened by flatMap in case of exception?

The Javadoc from Stream.flatMap (Function <T, Stream<U>> mapper) states: Stream.flatMap (Function <T, Stream<U>> mapper)的 Javadoc 指出:

Each mapped stream is closed after its contents have been placed into this stream.每个映射流在其内容放入此流后关闭。

Nice.好的。 But what about exception handling?但是异常处理呢?

Consider the following:考虑以下:

public List<Path> search (List<Path> paths) {
  return paths.stream ()
    .flatMap (dir -> {
      try {
        return Files.list (dir);
      } catch (IOException e) {
        throw new UncheckedIOException (e);
      }
    })
    .filter (this::mightThrowException)
    .collect (toList ());
}

If Files.list (Path) throws an exception on the first call, its stream is never opened in the first place, so doesn't need closing.如果Files.list (Path)在第一次调用时抛出异常,则它的流永远不会首先打开,因此不需要关闭。 If it throws an exception on a later call, the streams generated from previous calls have all been fully processed and closed by .flapMap () per its specification.如果它在以后的调用中抛出异常,则先前调用生成的流都已根据其规范由.flapMap ()完全处理和关闭。

But what happen if the filter throws an exception?但是如果过滤器抛出异常会发生什么? We're in the middle of processing a file listing stream, so I guess I need to close something somewhere, but I don't get what exactly.我们正在处理文件列表流,所以我想我需要在某处关闭一些东西,但我不明白到底是什么。 The initial paths.stream () maybe?最初的paths.stream ()可能吗? which would then call the close method on derived streams?然后会在派生流上调用 close 方法?

NB: for anyone not familiar with the Files.list (Path) static method, it returns a Stream<Path> that (unlike most streams) needs to be closed.注意:对于不熟悉Files.list (Path)静态方法的任何人,它返回一个Stream<Path> ,(与大多数流不同)需要关闭。

The source shows that the Stream returned to flatMap is immediately wrapped in a try with resources, so it will be closed even if a downstream operation throws an exception. 源码显示返回flatMapStream立即被包裹在 try with resources 中,所以即使下游操作抛出异常也会关闭。

It might be a good idea to update the flatMap javadoc to explicitly state that this will happen.更新flatMap javadoc 以明确说明会发生这种情况可能是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM