Class CloseableIterableStream<T>

java.lang.Object
com.azure.core.util.IterableStream<T>
com.azure.core.util.CloseableIterableStream<T>
Type Parameters:
T - The type of values in this stream.
All Implemented Interfaces:
Closeable, AutoCloseable, Iterable<T>

public final class CloseableIterableStream<T> extends IterableStream<T> implements Closeable
An IterableStream that provides deterministic cleanup for resource-backed iteration.

This stream takes ownership of the resource associated with the supplied iterable. After construction, manage the resource's lifetime through this stream rather than closing the resource directly.

Iteration behavior, including whether multiple iterators are supported, is determined by the supplied iterable. Use this stream in a try-with-resources statement to ensure that the owned resource is released whether iteration completes normally or ends early. Closing the stream is safe to do more than once.

Code sample

BufferedReader reader = getReader();
Iterable<String> lines = () -> reader.lines().iterator();

try (CloseableIterableStream<String> stream = new CloseableIterableStream<>(lines, reader)) {
    for (String line : stream) {
        System.out.println(line);
    }
} catch (IOException exception) {
    throw new UncheckedIOException("Failed to close the reader.", exception);
}
  • Constructor Details

    • CloseableIterableStream

      public CloseableIterableStream(Iterable<T> iterable, Closeable ownedResource)
      Creates an iterable stream that owns the resource associated with its iteration.
      Parameters:
      iterable - The iterable that reads values from, or is otherwise associated with, the owned resource.
      ownedResource - The resource whose ownership is transferred to this stream and which is released when this stream is closed.
      Throws:
      NullPointerException - If iterable or ownedResource is null.
  • Method Details

    • stream

      public Stream<T> stream()
      Gets a Java stream of values that closes this iterable stream when the returned stream is closed.

      Closing the returned Java stream also closes this iterable stream. If this iterable stream isn't managed with try-with-resources, the returned Java stream must be explicitly closed to release the owned resource. Terminal operations don't automatically close it.

      Overrides:
      stream in class IterableStream<T>
      Returns:
      A Java stream of values.
      Throws:
      UncheckedIOException - If closing the returned Java stream fails to close the owned resource.
    • close

      public void close() throws IOException
      Releases the resource owned by this stream.

      This method is idempotent.

      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Throws:
      IOException - If the owned resource fails to close.