Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

This code sometimes throws IllegalStateException: stream has already been operated upon or closed. Supplier is not used.

Java
Stream<Order> s = repo.findAll().stream();
long c = s.count();
List<Order> l = s.toList();

Explain and fix.

A stream can be consumed only once. count() is a terminal operation, so it consumes s, and the following s.toList() finds the stream already used and throws IllegalStateException. The fix is to collect to a list first and use the list for both the count and the data, or to create a new stream from the source each time, for example through a Supplier<Stream<Order>>. Storing streams in fields or returning them for several uses invites the same bug.

Why this question is asked

This exception is one of the first stream errors most developers meet, and the message is accurate but not very helpful: what does it mean for a stream to be operated upon, and why can we not just start again? Interviewers like the question because the fix is simple, but explaining it well shows that we understand what a stream is: a one-time pipeline over a source, not a collection. In this answer, we will recap why streams are single-use, reproduce the error, explain why it may appear only sometimes, go through the fixes and when each fits, and finish with the design habits that prevent it.

1A Quick Recap: A Stream Is Not a Collection

A collection, such as a List, stores elements; we can iterate over it as many times as we like. A stream does not store anything. It is a pipeline that pulls elements from a source, through a series of stages, into one terminal operation such as count, toList or forEach. Once the terminal operation has run, the pipeline has done its one job.

The reason for this design is that many sources can be read only once: lines from a file, rows from a database cursor, data from a network socket or an Iterator. Making every stream single-use gives all of them the same, predictable rule. Internally, each pipeline stage has a flag that is set as soon as the stage is linked to another operation or consumed; any later attempt to use it throws.

2Reproducing the Error

Here is the code from the question with what happens on each line.

Java
Stream<Order> s = repo.findAll().stream(); // a pipeline over the list, nothing read yet
long c = s.count(); // terminal operation: s is now consumed
List<Order> l = s.toList(); // java.lang.IllegalStateException:
// stream has already been operated upon or closed
Step throughLife of a stream object
  1. Created from a sourcelist.stream(), Files.lines(path), ...
  2. Intermediate operations link new stageseach stage can be linked only once
  3. Terminal operation runsthe pipeline is marked consumed
  4. Another operation on the same object?
    YesIllegalStateExceptionNoStream is discarded

4 steps in order. Play them, or step through them one at a time.

Notice that the error is not about the data. The list returned by findAll() is still there and could be streamed again. The problem is only that we kept the stream object in a variable and tried to run a second terminal operation on it.

3Why It Happens Only Sometimes

The question says the code sometimes throws. The check itself is not random: every second terminal operation on the same stream throws, every time. When the failure is intermittent, it is almost always because the second use sits on a path that runs only for some inputs, such as code that only builds the list when the count is above zero, or a log statement that counts the stream only at debug level.

Java
Stream<Order> s = repo.findAll().stream();
if (log.isDebugEnabled()) {
log.debug("orders: {}", s.count()); // consumes s, but only when debug logging is on
}
List<Order> l = s.toList(); // throws only in environments with debug enabled

This variant is a good one to mention in an interview, because it explains why the bug passed tests in one environment and failed in another.

4Fix 1: Collect to a List First

When we need the elements more than once, the natural fix is to materialise them once into a list and then ask the list for whatever we need. A list knows its size, so the count costs nothing.

Java
List<Order> l = repo.findAll(); // already a list; no stream needed for this
long c = l.size(); // 120
List<Order> open = repo.findAll().stream()
.filter(Order::isOpen)
.toList(); // one terminal operation
long openCount = open.size(); // 37, no second pass

Notice that in the original code, repo.findAll() already returns a list, so the stream added nothing. Using the list directly is both correct and cheaper. If we also need a filtered or transformed view, we collect once and reuse the result.

5Fix 2: A New Stream From the Source Each Time

If the two operations really need different pipelines, we create a fresh stream for each, from the same source. A Supplier<Stream<Order>> makes that convenient when the pipeline is built in one place and used in several.

Java
List<Order> all = repo.findAll();
Supplier<Stream<Order>> openOrders = () -> all.stream().filter(Order::isOpen);
long c = openOrders.get().count(); // 37, a new stream
List<Order> l = openOrders.get().toList(); // a second new stream, no exception

But there is a catch: each call runs the whole pipeline again. That is cheap over an in-memory list, but if the supplier calls the database, such as () -> repo.findAll().stream(), every get() runs a new query, and the two results may even disagree if data changed in between. For anything that reads from an external source, fix 1 is usually the better choice.

6Design Habits That Prevent It

The bug becomes likely whenever a stream escapes the line where it is created. Storing a Stream in a field, passing it to several methods, or returning one from a method that callers may use twice all invite a second terminal operation. A good habit is to treat a stream as a short-lived expression: create it, chain the operations and finish it in one statement. Methods should return collections, or a Supplier if laziness really matters. When a method does return a stream, for example a repository method that streams rows from a cursor, its documentation should say that it must be consumed once and closed, ideally in a try-with-resources block.

7Follow-up questions

Does close() have the same effect?

Yes. A closed stream cannot be used either, which is why the message says operated upon or closed. Streams from files, such as Files.lines, hold an open file handle and must be closed after use, usually with try-with-resources.

Is there a way to reset or copy a stream?

No. The API deliberately has no reset, because many sources cannot be replayed. If we need the data twice, we either store it in a collection or recreate the stream from a source that can be read again.

Why does the exception sometimes mention linking instead of consuming?

Because calling an intermediate operation on a stream that already has a downstream stage also counts as using it. For example, calling s.filter(...) twice on the same s throws, since each stage can be linked to only one next stage.

8Conclusion

In this answer, we saw that a stream is a one-time pipeline over a source, so count() consumed s and the later toList() threw IllegalStateException. The failure is deterministic and seems intermittent only when the second use sits on a conditional path. We fix it by collecting into a list once and reusing the list, or by creating a fresh stream from the source each time, for example with a Supplier, while remembering that each new stream reruns the pipeline. Keeping streams short-lived and returning collections from methods prevents the bug.

What to say in the interviewAbout 90 seconds aloud

Open with

A stream isn't a collection, it's a one-shot pipeline over a source. When we call a terminal operation like count, the pipeline runs and the stream object is marked as consumed, so calling toList on the same variable afterwards throws IllegalStateException: stream has already been operated upon or closed.

Then, if they want more

Streams are single-use on purpose, because many sources, like file lines or database cursors, can only be read once. The check isn't random, so when it happens only sometimes, it's usually because the first terminal operation is on a conditional path, for example a debug log that counts the stream only when debug logging is enabled.

To fix it, I'd first notice that repo findAll already returns a list, so I'd just use the list: size for the count and the list itself for the data. If I need a filtered result, I collect once with toList and take its size.

If I really need two different pipelines, I create a fresh stream from the source each time, and a Supplier of Stream is a convenient way to do that, but each get reruns the pipeline, so if the supplier calls the database, that's a second query and possibly different data.

More generally, I'd treat streams as short-lived expressions: don't store them in fields or return them for multiple uses; return collections instead, and if a method must return a stream, document that it's consumed once and closed.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code sometimes throws IllegalStateException: stream has already been operated upon...": https://scrivio-interview-library.netlify.app/java/streams/54d4a6a967/