Course contentsShow
← Java
Lesson 1380 of 2,87031. Streams API: Creation and BasicsFree lesson

Stateful vs Stateless Stream Generation

Understand thread-safety differences between stateless generation and mutable state in suppliers.

Stateful vs Stateless Stream Generation

What you'll learn: You'll understand the crucial thread-safety differences between stateless generation and mutable state in stream suppliers.

When you generate streams with Stream.generate() or Stream.iterate(), the behavior of your supplier can be stateless or stateful—and this distinction has major implications for thread safety and parallel processing.

Stateless Generation

A stateless supplier produces elements independently, without relying on mutable shared state. Each invocation stands alone:

Stream<Double> random = Stream.generate(Math::random);

This is thread-safe because Math.random() doesn't depend on any state you're managing. Every call is independent.

Stateful Generation

A stateful supplier relies on mutable state that changes between invocations:

AtomicInteger counter = new AtomicInteger(0);
Stream<Integer> counted = Stream.generate(counter::incrementAndGet);

This works sequentially, but becomes problematic in parallel streams. Multiple threads might access and modify the counter simultaneously, leading to unpredictable results even with thread-safe classes like AtomicInteger.

The Thread-Safety Problem

Think of stateless generation like a vending machine that always dispenses random items—each customer's experience is independent. Stateful generation is like a ticket dispenser: it must track the last number given. If multiple people pull tickets simultaneously without proper coordination, you might get duplicates or skipped numbers.

Stream.iterate() is inherently stateful (each element depends on the previous one) and is designed for sequential processing. Using it in parallel streams doesn't make sense and won't parallelize effectively.

When to Use Each

  • Stateless: Random values, constant values, truly independent computations—safe for parallel streams
  • Stateful: Sequential counters, accumulators—use only in sequential streams

Key Takeaway: Stateless stream generation is thread-safe and parallelizable; stateful generation with mutable state should be avoided in parallel streams to prevent race conditions and unpredictable behavior.