When using Java threads in a project, I tried to reuse the thread as such.
I'll start with a set of objects, then do some filtering.
Collection<MyClass> collection = ; Stream<MyClass> myStream = collection.stream().filter();
Then I want to reuse the same thread several times. For example, at first I want to just get the first element from the stream, as such.
MyClass first = myStream.findFirst().get();
Then I do some other things, and later I want to use the filtered myStream
to perform operations on each object in the stream.
myStream.forEach();
However, when I try to do this, I get this error.
java.lang.IllegalStateException: stream has already been operated upon or closed
I can solve the problem by doing one of the following:
- Create a new stream from the source collection and filter it again
- Collect the stream into a filtered collection, then create the stream on
So, I think there are several questions that I based on my findings.
- If you cannot reuse streams, then when will it ever be useful to return a stream instance for later use?
- Is it possible to clone threads so that they can be reused without raising an
IllegalStateException
?
source share