“Stream has already been operated upon or closed” Exception in Java

1. Overview

In this brief article, we’re going to discuss a common Exception that we may encounter when working with the Stream class in Java 8:

IllegalStateException: stream has already been operated upon or closed.

We’ll discover the scenarios when this exception occurs, and the possible ways of avoiding it, all along with practical examples.

2. The Cause

In Java 8, each Stream class represents a single-use sequence of data and supports several I/O operations.

Stream should be operated on (invoking an intermediate or terminal stream operation) only once. A Stream implementation may throw IllegalStateException if it detects that the Stream is being reused.

Whenever a terminal operation is called on a Stream object, the instance gets consumed and closed.

Therefore, we’re only allowed to perform a single operation that consumes a Stream, otherwise, we’ll get an exception that states that the Stream has already been operated upon or closed.

Let’s see how this can be translated to a practical example:

Stream<String> stringStream = Stream.of("A", "B", "C", "D");
Optional<String> result1 = stringStream.findAny(); 
System.out.println(result1.get()); 
Optional<String> result2 = stringStream.findFirst();

As a result:

A
Exception in thread "main" java.lang.IllegalStateException: 
  stream has already been operated upon or closed

After the #findAny() method is invoked, the stringStream is closed, therefore, any further operation on the Stream will throw the IllegalStateException, and that’s what happened after invoking the #findFirst() method.

3. The Solution

Simply put, the solution consists of creating a new Stream each time we need one.

We can, of course, do that manually, but that’s where the Supplier functional interface becomes really handy:

Supplier<Stream<String>> streamSupplier 
  = () -> Stream.of("A", "B", "C", "D");
Optional<String> result1 = streamSupplier.get().findAny();
System.out.println(result1.get());
Optional<String> result2 = streamSupplier.get().findFirst();
System.out.println(result2.get());

As a result:

A
A

We’ve defined the streamSupplier object with the type Stream<String>, which is exactly the same type which the #get() method returns. The Supplier is based on a lambda expression that takes no input and returns a new Stream.

Invoking the functional method get() on the Supplier returns a freshly created Stream object, on which we can safely perform another Stream operation.

5. Conclusion

In this quick tutorial, we’ve seen how to perform terminal operations on a Stream multiple times, while avoiding the famous IllegalStateException that is thrown when the Stream is already closed or operated upon.

You can find the complete source code and all code snippets for this article over on GitHub.

Related posts:

Java Program to Implement LinkedList API
How to Find an Element in a List with Java
Java Program to Generate a Graph for a Given Fixed Degree Sequence
Custom HTTP Header with the HttpClient
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Java Program to Implement Bubble Sort
Dynamic Proxies in Java
Create Java Applet to Simulate Any Sorting Technique
RestTemplate Post Request with JSON
Java Program to Implement Hash Tables Chaining with Binary Trees
Java Program to Generate Random Numbers Using Probability Distribution Function
How to Kill a Java Thread
Guide to Apache Commons CircularFifoQueue
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to implement Bi Directional Map
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
String Processing with Apache Commons Lang 3
Spring Security Basic Authentication
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Disable Spring Data Auto Configuration
Spring Autowiring of Generic Types
Java Program to Implement Trie
Spring Boot - Batch Service
Custom Thread Pools In Java 8 Parallel Streams
Registration – Password Strength and Rules
Quick Guide on Loading Initial Data with Spring Boot
Quick Guide to the Java StringTokenizer
Java Program to Implement LinkedBlockingDeque API
Summing Numbers with Java Streams
Convert Hex to ASCII in Java
Java Program to Implement Insertion Sort
Java Program to Implement LinkedHashMap API