Class CloseableIterableStream<T>
- Type Parameters:
T- The type of values in this stream.
- All Implemented Interfaces:
Closeable, AutoCloseable, Iterable<T>
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 Summary
ConstructorsConstructorDescriptionCloseableIterableStream(Iterable<T> iterable, Closeable ownedResource) Creates an iterable stream that owns the resource associated with its iteration. -
Method Summary
Methods inherited from class IterableStream
iterator, ofMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Iterable
forEach, spliterator
-
Constructor Details
-
CloseableIterableStream
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- IfiterableorownedResourceisnull.
-
-
Method Details
-
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:
streamin classIterableStream<T>- Returns:
- A Java stream of values.
- Throws:
UncheckedIOException- If closing the returned Java stream fails to close the owned resource.
-
close
Releases the resource owned by this stream.This method is idempotent.
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- If the owned resource fails to close.
-