A parallel stream may invoke forEach actions in any thread and order; forEachOrdered preserves encounter order when one exists.
Java parallel streams: forEach and forEachOrdered have different order contracts
Keep computation separate from ordered output
A shipment list has encounter order. Parallel forEach does not promise its actions run in that order, so writing numbered report lines from it can scramble the report. forEachOrdered preserves encounter order for this ordered source, though the ordering constraint can reduce parallel benefit.
The program deliberately prints only the ordered path. An unordered call cannot have one portable expected output. peek actions and parallel terminal callbacks should not be treated as an audit log.
Parallel does not make side effects safe
A non-thread-safe accumulator can lose updates regardless of which terminal method prints in order. Use a collector or reduction for values. Choose parallelism only after measuring enough CPU work to offset splitting, coordination and combining costs.
Working program
import java.util.Arrays;
import java.util.List;
public class OrderedShipmentReport {
public static void main(String[] args) {
List<String> shipmentIds = Arrays.asList("SH-47", "SH-82", "SH-91");
shipmentIds.parallelStream().forEachOrdered(System.out::println);
}
}Output
SH-47
SH-82
SH-91Cost and ownership
The traversal remains O(n) total work. Parallel execution can use additional worker threads and coordination, while preserving encounter order limits throughput. Three strings are too little work to justify parallelism; the small fixture isolates the contract.
Common Mistakes
- Do not promise forEach output order on a parallel stream.
- Do not use forEachOrdered to make a shared mutable accumulator thread-safe.
- Do not assume parallel traversal is faster for small or blocking workloads.
Read next
Java streams: lazy pipelines and bounded results, Java Stream.peek: observation is not a correctness hook, stream reduce identity, Java Collectors.toMap: preserve encounter order with LinkedHashMap.
Continue with: Java parallel streams: reduce values instead of mutating shared results, Java RecursiveTask: split work only above a measured threshold.
