Side effects and why they break streams
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A side effect is any change a lambda makes outside itself: adding to an outside list, raising a counter, putting a key in a map. Streams are built for lambdas that only take a value and return a result, and side effects make pipelines skip work, give wrong totals or lose data.
What a side effect is
Compare two lambdas. m -> m * 2 reads m and returns a new value; nothing else in the program changes. m -> list.add(m) changes list, which lives outside the lambda. The second one has a side effect.
Example 1 · The compiler blocks the simplest side effect
import java.util.List;
public class TotalErrorDemo { public static void main(String[] args) { List<Integer> fees = List.of(1200, 800, 500); int total = 0; fees.forEach(f -> total += f); System.out.println(total); }}TotalErrorDemo.java:7: error: local variables referenced from a lambda expression must be final or effectively final
fees.forEach(f -> total += f);
^
1 errorWhat this code does
- A lambda may read a local variable only if it never changes after it is set, which is called effectively final.
total += fchangestotal, so the code does not compile. - The fix is not a trick to get around the rule, such as an
int[]. It is to ask the stream for the answer:fees.stream().mapToInt(Integer::intValue).sum().
A function with no side effects, whose result depends only on its input, is called a pure function. Pure lambdas are easy to test and safe to run in any order, any number of times, on any thread. You already met the compiler guard for the simplest case: a lambda cannot change a local variable, so marks.forEach(m -> total += m) does not compile. But the guard only checks local variables. An outside ArrayList, a HashMap, a field, a one-element int[] or an AtomicInteger can still be changed from inside a lambda, and that is where the bugs start.
Fix the error
Fix the lambda counter
Read the real compiler error, then pick the line that fixes it.
Add up the fees without changing a variable inside the lambda.
Error
TotalFix.java:7: error: local variables referenced from a lambda expression must be final or effectively final
fees.forEach(f -> total += f);
^Stateless lambdas and why streams expect them
A stateless lambda does not remember anything between calls: its answer for one element does not depend on earlier elements. The stream API is designed around this rule.
Example 2 · A counter inside map may never run
import java.util.List;
public class SkippedWorkDemo { public static void main(String[] args) { List<String> names = List.of("aarav", "priya", "rohan", "kavya"); int[] calls = {0}; // a workaround that the compiler allows
long count = names.stream() .map(s -> { calls[0]++; // side effect return s.toUpperCase(); }) .count();
System.out.println("count = " + count); System.out.println("map was called " + calls[0] + " times");
long passed = names.stream() .filter(s -> { calls[0]++; return s.length() == 5; }) .count(); System.out.println("passed = " + passed + ", calls now " + calls[0]); }}count = 4 map was called 0 times passed = 4, calls now 4
What this code does
mapcannot change how many elements there are, and a list knows its size, socount()returns 4 without runningmapat all (Java 9 and later). The side effect simply never happens.- With
filterthe count really depends on each element, so the lambda runs 4 times. Whether a side effect runs is a detail of the library, so code must never depend on it.
The stream uses that freedom in three ways. First, a stream may skip work. Since Java 9, count() on a list stream can return the size directly without running map at all, so a counter inside map stays 0. Second, a short-circuiting step such as findFirst stops early, so later elements never reach your lambda. Third, a parallel stream, one that splits the work across several threads, calls your lambda from many threads at once and in no fixed order. A lambda with a side effect silently depends on all three: that every element is visited, once, in order, on one thread. None of that is promised.
forEach is a side effect too, and it is fine: showing the result is the point of the program. The rule is about the lambdas in the middle of the pipeline and about building results.Trap: adding to an ArrayList from a parallel stream
The common beginner pattern is stream.forEach(x -> results.add(x)). In a normal stream it works, but it hides the intent and blocks any later move to parallel.
Example 3 · Trap: a shared ArrayList in a parallel stream
import java.util.ArrayList;import java.util.List;import java.util.stream.IntStream;
public class SharedListDemo { public static void main(String[] args) { for (int run = 1; run <= 5; run++) { List<Integer> tickets = new ArrayList<>(); try { IntStream.range(0, 10_000).parallel().forEach(i -> tickets.add(i)); System.out.println("Run " + run + ": size " + tickets.size()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Run " + run + ": crashed with ArrayIndexOutOfBoundsException"); } } }}Run 1: size 9888 Run 2: size 3253 Run 3: crashed with ArrayIndexOutOfBoundsException Run 4: size 5881 Run 5: size 5532
What this code does
- Every run should add exactly 10000 tickets. Several threads call
tickets.addat the same moment, overwrite each other and lose items; some runs crash while the list grows. One lucky run can even look correct. - The bug depends on timing and on the number of CPU cores, so it may pass on one machine and fail on a server. That is why "it worked when I tried it" is no proof for shared state.
Example 4 · Fix: let the stream build the list
import java.util.List;import java.util.stream.IntStream;
public class CollectFixDemo { public static void main(String[] args) { for (int run = 1; run <= 3; run++) { List<Integer> tickets = IntStream.range(0, 10_000) .parallel() .boxed() .toList(); System.out.println("Run " + run + ": size " + tickets.size() + ", first five " + tickets.subList(0, 5) + ", last " + tickets.get(tickets.size() - 1)); }
int total = IntStream.rangeClosed(1, 100).parallel().sum(); System.out.println("Parallel sum 1 to 100: " + total); }}Run 1: size 10000, first five [0, 1, 2, 3, 4], last 9999 Run 2: size 10000, first five [0, 1, 2, 3, 4], last 9999 Run 3: size 10000, first five [0, 1, 2, 3, 4], last 9999 Parallel sum 1 to 100: 5050
What this code does
- With
toList()each thread fills its own private part and the stream joins the parts at the end, in the original order. No list is shared, so every run gives all 10000 items. sum()works the same way: each thread adds its own chunk, then the chunk totals are added. The result is always 5050.
With .parallel() it breaks. ArrayList is not thread-safe: it is not built for two threads changing it at the same time. Two threads can write into the same slot, so items go missing. Sometimes both grow the inner array at once and the program throws ArrayIndexOutOfBoundsException. Each run gives a different size, so the bug may not even show up on your laptop. Wrapping the list with Collections.synchronizedList stops the crash but makes the threads wait for each other, and the order is still random. The real fix is to let the stream build the list itself.
Replacing side effects with collect or reduce
Almost every side effect has a ready-made stream replacement. The stream then builds the result itself, safely, even in parallel, because each thread fills its own part and the parts are merged at the end.
Example 5 · From forEach with a map to groupingBy
import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;
record Mark(String roll, String status) { }
public class AttendanceCountDemo { public static void main(String[] args) { List<Mark> today = List.of( new Mark("101", "Present"), new Mark("102", "Absent"), new Mark("103", "Present"), new Mark("104", "Late"), new Mark("105", "Present"), new Mark("106", "Absent"));
// side effect: the lambda changes an outside map Map<String, Integer> counts = new HashMap<>(); today.forEach(m -> counts.merge(m.status(), 1, Integer::sum)); System.out.println("With forEach: " + new TreeMap<>(counts));
// no side effect: the collector builds the map Map<String, Long> grouped = today.stream() .collect(Collectors.groupingBy(Mark::status, TreeMap::new, Collectors.counting())); System.out.println("With groupingBy: " + grouped);
long present = today.stream().filter(m -> m.status().equals("Present")).count(); System.out.println("Present: " + present + " of " + today.size()); }}With forEach: {Absent=2, Late=1, Present=3}
With groupingBy: {Absent=2, Late=1, Present=3}
Present: 3 of 6What this code does
- Both give the same counts here, but only the
groupingByversion is safe to make parallel and says its goal in one line: "count by status". - The
forEachversion needs an outside map, the right merge rule and a copy into aTreeMapfor a fixed print order. The collector does all three, andTreeMap::newkeeps the keys sorted.
forEach(x -> list.add(x))→.toList()or.collect(Collectors.toList()).- A counter in
forEach→.count(); a running total →.mapToInt(...).sum()orreduce. forEach(x -> map.merge(key, 1, Integer::sum))→Collectors.groupingBy(key, Collectors.counting()).- Tracking the best value in an
int[]→.max(); aseenset insidefilter→.distinct().
Next step
Check your understanding
11 quick questions