src/share/classes/java/util/stream/BaseStream.java

Print this page
rev 7633 : 8017513: Support for closeable streams
Reviewed-by:
Contributed-by: brian.goetz@oracle.com

@@ -22,10 +22,11 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
 package java.util.stream;
 
+import java.util.MayHoldCloseableResource;
 import java.util.Iterator;
 import java.util.Spliterator;
 
 /**
  * Base interface for stream types such as {@link Stream}, {@link IntStream},

@@ -33,11 +34,12 @@
  *
  * @param <T> type of stream elements
  * @param <S> type of stream implementing {@code BaseStream}
  * @since 1.8
  */
-public interface BaseStream<T, S extends BaseStream<T, S>> {
+public interface BaseStream<T, S extends BaseStream<T, S>>
+        extends MayHoldCloseableResource {
     /**
      * Returns an iterator for the elements of this stream.
      *
      * <p>This is a <a href="package-summary.html#StreamOps">terminal
      * operation</a>.

@@ -101,6 +103,20 @@
      * operation</a>.
      *
      * @return an unordered stream
      */
     S unordered();
+
+    /**
+     * Returns an equivalent stream with an additional close handler.  Close
+     * handlers are run when the {@link MayHoldCloseableResource#close()} method
+     * is called on the stream, and are executed in the order they were
+     * added.  All close handlers are run, even if earlier close handlers throw
+     * exceptions.  If any close handler throws an exception, the first
+     * exception thrown will be relayed to the caller of {@code close()}, with
+     * any remaining exceptions added to that exception as suppressed exceptions.
+     *
+     * @param closeHandler A task to execute when the stream is closed
+     * @return a stream with a handler that is run if the stream is closed
+     */
+    S onClose(Runnable closeHandler);
 }