Skip to content

Stream resource management with AutoCloseable

In Java 8, the Stream interface extends BaseStream, which in turn extends the AutoCloseable interface^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md]. This inheritance allows stream resources to be managed explicitly using try-with-resources constructs, ensuring that any registered handlers are executed upon completion^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md].

Resource Management

Because Stream is AutoCloseable, developers can wrap stream operations in a try block to handle cleanup automatically^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md]. The Stream.onClose(Runnable) method is used to register one or more actions that should be triggered when the stream is closed^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md].

If multiple handlers are registered, they are executed in the order they were added^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md]. However, if an exception is thrown within a handler, it will prevent subsequent handlers from running^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md].

Usage Example

The following pattern demonstrates how to combine try-with-resources with onClose to manage side effects:

try (Stream<String> stream = list.stream()) {
  stream.onClose(() -> {
    System.out.println("1");
    throw new NullPointerException("1 exception");
  }).onClose(() -> {
    System.out.println("2");
    throw new NullPointerException("2 exception");
  }).forEach(System.out::println);
}

In the example above, the first handler prints "1" and throws an exception^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md]. This prevents the second handler (printing "2") from executing^[600-developer-java-java8-java8-stream.md, 600-developer__java__java8__java8-stream.md].

  • [[Try-with-resources]]
  • [[Java Streams]]
  • [[BaseStream]]

Sources

  • 600-developer-java-java8-java8-stream.md
  • 600-developer__java__java8__java8-stream.md