Video in progress
Is it right to return a Stream<T> from a service or repository method, or should you always return a List?
Returning a Stream is lazy and convenient for large volumes, but it puts responsibility on the caller: it is single-use, may need closing, and is tied to an open resource (a transaction, a cursor). Within a module that's fine, but across a module or transaction boundary I usually return a List or a paged result.
📖 Answer
Returning a Stream is an agreement in itself. The caller has to know:
- It can be traversed only once.
- Whether there is a resource behind it and who closes it.
- When it "starts working": because of laziness, the error appears in the caller's code, not in your method.
The third is especially confusing:
@Transactional(readOnly = true)
public Stream<Order> findForExport() {
return repo.streamAll(); // the transaction ends when the method returns
}
// in the controller .forEach(...): the connection is already closed
The cost of returning a List: everything is loaded into memory. For 50 elements that's not a problem; for 5 million it is.
My decisions:
- Private/package methods inside a module:
Streamis fine, the lifecycle is visible in one place. - The service layer's public API:
List,Page<T>orSlice<T>. If you need large volume, use a callback style:void forEachOrder(Consumer<Order> action): the method itself opens and closes the resource, and the caller can't get it wrong. - Between modules or services: no streams at all, but pagination or an asynchronous export (a file, a queue).
@Transactional(readOnly = true)
public void exportOrders(Consumer<OrderRow> sink) {
try (Stream<Order> s = repo.streamAll()) {
s.map(OrderRow::from).forEach(sink);
}
}
If you return a Stream anyway, write "must be closed" in the Javadoc and tie the resource to it with onClose. Effective Java also recommends returning a collection by default, because a Collection gives both iteration and a stream, while a Stream gives only one.
Sign up to mark studied questions and save your progress.