Modern Java from Zero — Features by Version, Streams & Concurrency
"Most Java written today still looks like Java 8. This chapter shows what changed, how streams really run, and how to make code run at the same time without breaking."
01 · Why this chapter existsMost Java Written Today Still Looks Like Java 8
Two bugs shipped in the same week at QuickBite, a food-delivery start-up, and neither one needed a clever mistake. Both came from using a tool without knowing how it runs. This chapter exists so you can see, before the bug, how streams and threads actually work, and which Java release gave you which tool.
It is Friday dinner rush. The "revenue by restaurant" report for the owners' dashboard takes too long, so a developer "speeds it up". The change is one word: stream() becomes parallelStream(). The report adds each order's total into a shared HashMap, one entry per restaurant.
The report is fast now. It is also wrong. Every refresh shows a different total for the same day. Once, the endpoint fails with a ConcurrentModificationException. In production the totals were off by a few thousand rupees, small enough that nobody noticed for hours.
The same week a second bug hides in checkout. A CompletableFuture chain calls the price service, and then charges the customer. The price service has a bad deploy and throws. Nothing is logged. Nothing is returned. The customer sees a spinner until the app gives up.
The two incidents look unrelated. One is about streams, the other about asynchronous code. The root is the same: the code was written from a pattern, not from a picture of what runs where. We will reproduce both in miniature, with real output, before explaining anything.
Incident one: the shared HashMap
First, the data. The next program makes 2,000,000 synthetic sales with a fixed random seed (Random(42)), so every run starts from the same data. Each sale belongs to one of three restaurants and costs between ₹100 and ₹500, kept as integer paise (₹1 = 100 paise). It computes the right answer with a sequential stream, then runs the "fast" version five times.
The setup: the only line that matters is the forEach with merge. merge(key, value, function) means: if the key is missing, store the value; if it is present, store function(old, value). Here the function adds the numbers. The three lines below are the whole bug.
sales.parallelStream()
.forEach(s -> totals.merge(s.restaurant(), (long) s.cents(), Long::sum));The full program follows. It is about 30 lines. Read it once for the shape: build the data, compute the expected answer the safe way, then try the unsafe way five times and compare.
import java.util.*;
import java.util.stream.*;
public class FridayReport {
record Sale(String restaurant, int cents) {}
public static void main(String[] args) {
String[] names = {"Spice Hut", "Dosa Corner", "Pizza Lane"};
Random rnd = new Random(42);
List<Sale> sales = new ArrayList<>();
for (int i = 0; i < 2_000_000; i++) {
sales.add(new Sale(names[rnd.nextInt(3)], 10_000 + rnd.nextInt(40_000)));
}
Map<String, Long> expected = sales.stream()
.collect(Collectors.groupingBy(Sale::restaurant, TreeMap::new,
Collectors.summingLong(Sale::cents)));
System.out.println("expected: " + expected);
for (int run = 1; run <= 5; run++) {
Map<String, Long> totals = new HashMap<>();
try {
sales.parallelStream()
.forEach(s -> totals.merge(s.restaurant(), (long) s.cents(), Long::sum));
System.out.println("run " + run + ": " + new TreeMap<>(totals)
+ (totals.equals(expected) ? " (right)" : " (WRONG)"));
} catch (Exception e) {
System.out.println("run " + run + ": " + e);
}
}
}
}Make the invisible visible: the output of the first batch of five runs on the course machine. I ran the program three times (15 runs in all). No run in the 15 was right: 13 printed a wrong total and 2 threw ConcurrentModificationException. Section 07 repeats the experiment in a separate program, again with 3 keys: all 15 runs gave a wrong total and none threw, so the exception is a matter of timing.
expected: {Dosa Corner=20013996426, Pizza Lane=20024594215, Spice Hut=19994522886}
run 1: {Dosa Corner=7341288481, Pizza Lane=7677714602, Spice Hut=10002367060} (WRONG)
run 2: {Dosa Corner=8781354120, Pizza Lane=6186735653, Spice Hut=5986670152} (WRONG)
run 3: {Dosa Corner=8571778976, Pizza Lane=8429204016, Spice Hut=9119844905} (WRONG)
run 4: {Dosa Corner=7362965202, Pizza Lane=7677492611, Spice Hut=8330665391} (WRONG)
run 5: {Dosa Corner=7307807819, Pizza Lane=7193468343, Spice Hut=8841718150} (WRONG)Read the first run. The right answer for Dosa Corner is 20,013,996,426 paise, about ₹200 million. The parallel run reported 7,341,288,481. The three restaurants together should come to about ₹600 million, and the run reported about ₹250 million. More than half of the money disappeared, and the program printed no error.
In production the loss was only a few thousand rupees. Our miniature is much worse because it has only three keys and every core is writing to them at once. The real report had many more keys, so two threads rarely touched the same entry. The bug was the same in both. It was just easier to miss with fewer collisions.
Why: totals.merge looks like one step, but inside it does three: read the old number, add, write the new number. Two threads can both read the same old number, both add, and both write. The second write overwrites the first, and one addition is lost. A plain HashMap has no protection against this. Sometimes the map also notices that another thread changed it in the middle of a merge, and it throws ConcurrentModificationException instead. Sections 07 and 08 draw this picture slowly.
The fix: do not share the map. Let the stream build it. collect(groupingBy(...)) gives each worker its own small map and merges those maps at the end, so no two threads ever touch the same one.
import java.util.*;
import java.util.stream.*;
public class FridayFix {
record Sale(String restaurant, int cents) {}
public static void main(String[] args) {
String[] names = {"Spice Hut", "Dosa Corner", "Pizza Lane"};
Random rnd = new Random(42);
List<Sale> sales = new ArrayList<>();
for (int i = 0; i < 2_000_000; i++) {
sales.add(new Sale(names[rnd.nextInt(3)], 10_000 + rnd.nextInt(40_000)));
}
Map<String, Long> expected = sales.stream()
.collect(Collectors.groupingBy(Sale::restaurant, TreeMap::new,
Collectors.summingLong(Sale::cents)));
for (int run = 1; run <= 5; run++) {
Map<String, Long> totals = sales.parallelStream()
.collect(Collectors.groupingBy(Sale::restaurant, TreeMap::new,
Collectors.summingLong(Sale::cents)));
System.out.println("run " + run + ": " + totals
+ (totals.equals(expected) ? " (right)" : " (WRONG)"));
}
}
}run 1: {Dosa Corner=20013996426, Pizza Lane=20024594215, Spice Hut=19994522886} (right)
run 2: {Dosa Corner=20013996426, Pizza Lane=20024594215, Spice Hut=19994522886} (right)
run 3: {Dosa Corner=20013996426, Pizza Lane=20024594215, Spice Hut=19994522886} (right)
run 4: {Dosa Corner=20013996426, Pizza Lane=20024594215, Spice Hut=19994522886} (right)
run 5: {Dosa Corner=20013996426, Pizza Lane=20024594215, Spice Hut=19994522886} (right)Five runs, five right answers, and the same parallelism. The fix did not make the stream slower or serial. It changed who owns the data while the work is running. That idea, give each worker its own data and combine at the end, comes back many times in this chapter (idiom pat-no-shared-state, section 07).
Incident two: the failure nobody saw
Now the checkout. The real code was longer, but the shape is this: ask the price service for the order's price, then charge. We will make the price service fail for order 7 and watch what the program tells us.
import java.util.concurrent.*;
public class SilentSpinner {
static int priceCents(int orderId) {
if (orderId == 7) throw new IllegalStateException("price service down");
return 54700;
}
public static void main(String[] args) throws Exception {
CompletableFuture<Void> checkout = CompletableFuture
.supplyAsync(() -> priceCents(7))
.thenAccept(c -> System.out.println("charging " + c));
Thread.sleep(500); // the "request" waits here
System.out.println("500 ms later: done=" + checkout.isDone()
+ ", failed=" + checkout.isCompletedExceptionally());
}
}Make the invisible visible: what the program prints. Notice that there is no stack trace and no log line.
500 ms later: done=true, failed=trueThe exception was not lost. It was stored inside the CompletableFuture: isCompletedExceptionally() says true. But a stored exception prints nothing by itself. The charging step, thenAccept, was skipped because the step before it failed, and nobody called a method that would look at the failure. If the HTTP request was waiting for the charge to finish, it waited for something that would never happen.
A real service must decide what to do with that stored exception: log it, return a fallback, or fail the request. Section 11 shows the three tools for that (exceptionally, handle, whenComplete) and the rule that goes with them (pat-cf-handle-errors).
Two bugs, one root
Both bugs came from not knowing where code runs and who owns the data. In the first, the data (a map) was owned by many threads at once. In the second, the error was owned by a future that nobody asked. The fix in each case was not a trick. It was a picture: a stream splits its work and merges the results; a future holds either a value or a failure.
That is the plan of the chapter. First we learn which tools each Java release gave you, so you can read old code and write new code. Then we build streams from nothing. Then we build concurrency from nothing. Every idea gets a program, and every program's output comes from a real run.
The chapter map
Figure 21.1 shows the three parts and the two places where they touch. Streams are built from lambdas, which arrived in Java 8, so Part 2 leans on Part 1. A parallel stream runs on a shared thread pool, so Part 2 also leans on Part 3.
Read the figure left to right as a learning order, not as a call graph. You can read Part 2 without Part 3 if you never use parallel streams, but you cannot use parallel streams safely without Part 3. That is why section 07 sits at the end of Part 2 and points forward.
How this chapter relates to E1, E2 and E3
The Engineering track already has three Java chapters. This one does not replace them. It fills the gap between them: E1 teaches the language, E3 drills hard interview questions on concurrency, and nothing taught streams and threads from zero, or listed which release added what.
| Chapter | What it does | What E21 adds | Go there when |
|---|---|---|---|
| E1 · Java Primer | Syntax, collections, memory, the JVM basics. | Features by version and a from-zero build of streams and concurrency, which E1 does not cover. | You need classes, generics or collections first: collections, how the JVM works. |
| E2 · Java Deep Dive | The Java memory model, virtual threads and Loom internals, modern Java at depth. | The picture and a runnable demo before the theory. | You want the formal rules: memory model, Loom, modern Java. |
| E3 · Java Interview Drill | 80 concurrency questions and many more, at interview depth. | The teaching layer underneath: build each idea from nothing. We link E3 and never repeat its questions. | You can already write a thread pool and want the sharp follow-ups: threads, java.util.concurrent. |
| E4 · Spring Boot | A framework that hides thread pools behind annotations. | What those pools are, so the defaults stop being magic. | You are tuning a real service. |
| E8 · Databases | SQL, indexes, transactions. | When a collector is the wrong tool and the database should aggregate. | A stream pipeline starts to look like GROUP BY. |
A last connection, because the course also covers Python. E20 handles concurrency with an event loop, and E19 explains why Python threads share one lock. Java's answer is real threads that run in parallel on every core, which is exactly why shared data needs the care described here.
How to read this chapter
The chapter has two halves. The first half is a primer in twelve sections. The second half is a drill of 100 interview questions with collapsed answers. A section in the primer follows the same shape each time, so you always know where you are.
- Incident first: each section starts with a small story and a real run that fails. You see the bug before you see the cure.
- Bridges: short sub-sections called "one level down" open the mechanism: what a lambda really is, what a stream does between two method calls, what a thread owns.
- Idioms: each primer section ends with named idioms such as
pat-no-shared-state. There are 27 in total, so you leave with a vocabulary you can use in a code review. Section 17 lists them all on one page. - Compile proofs and run proofs: when this chapter says a feature "arrived in Java 16", it shows
javac --release 15failing andjavac --release 16working. When it says a program is slow or wrong, it shows the run. - Drill, sections 13 to 15: 100 questions marked K (knowledge), S (scenario) or D (design). Each answer opens with a strong answer, then a picture, then a one-sentence "land it", then four likely follow-ups.
About the numbers. Every output on this page was produced on the course machine: 12 cores, about 7 GB of memory, JDK 25.0.5 as the default, and JDK 8, 17 and 21 for the "this did not exist yet" proofs. Timings are marked "measured on the course machine" because your machine will give different numbers. The shape of the result (which is faster, by roughly how much) is what matters.
About names. QuickBite's orders, lines and restaurants are the same sample data in every section, so the examples feel like one small system. Money is always integer paise. When you see priceCents, read it as paise, a naming habit kept the same as in the Python chapters.
About the word "version". Java ships a new release every six months, in March and September. Some releases are marked LTS, which means long-term support: vendors keep patching them for years. The LTS releases are 8, 11, 17, 21 and 25. Most companies move from one LTS to the next, so most of this chapter's compile proofs sit just below an LTS or just above one.
02 · Java 8 to 17Java 8 to 17: What Each Release Gave You, in One-Liners
Java did not change slowly between 2014 and 2021. It changed in many small steps, and each step removed some ceremony from daily code. This section walks the steps in order, shows the exact release that introduced each one, and lets you check every claim with a compiler.
A new developer joins QuickBite and gets two tickets on the same day. The first is in the billing service, written in 2016 on Java 8. The second is in the new orders service, written this year on Java 17. Both tickets say the same thing: "print the orders sorted by total, biggest first, with a plain word for each status".
The billing code is 63 lines. The orders code is 24 lines. They print the same three lines. The developer reads the first for ten minutes before finding the one line that sorts. The second takes one minute. Nothing about the problem changed. The language did.
First, the heart of the difference, in the first five lines of each file. The Java 8 version needs a whole class with private fields, a constructor and getters, and the real version also needs equals, hashCode and toString. The Java 17 version needs one line.
Java 8
A class that only holds data. Fields, constructor and getters are written by hand.
static class Order {
private final int id;
private final String customer;
Order(int id, String customer) {
this.id = id;
this.customer = customer;
}
public int getId() { return id; }
public String getCustomer() {
return customer;
}
// equals, hashCode, toString:
// about 20 more lines
}Java 17
The same class, called a record. One line, and the compiler adds the rest.
record Order(int id, String customer) {}The shift: a record is a class whose only job is to carry data, and the compiler writes the boring methods for you.
Now both complete programs. They create three orders, sort them by total (biggest first), and print the id, the customer and a plain word for the status. The left one was compiled and run with JDK 8, the right one with JDK 17, so you know neither is cheating.
import java.util.*;
public class OldStyle8 {
static class Order {
private final int id;
private final String customer;
private final int totalCents;
private final String status;
Order(int id, String customer, int totalCents, String status) {
this.id = id;
this.customer = customer;
this.totalCents = totalCents;
this.status = status;
}
public int getId() { return id; }
public String getCustomer() { return customer; }
public int getTotalCents() { return totalCents; }
public String getStatus() { return status; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order x = (Order) o;
return id == x.id && totalCents == x.totalCents
&& customer.equals(x.customer) && status.equals(x.status);
}
@Override public int hashCode() {
return Objects.hash(id, customer, totalCents, status);
}
@Override public String toString() {
return "Order{id=" + id + ", customer=" + customer + ", totalCents="
+ totalCents + ", status=" + status + "}";
}
}
static String label(String status) {
String text;
if (status.equals("DELIVERED")) {
text = "done";
} else if (status.equals("PREPARING")) {
text = "cooking";
} else {
text = "other";
}
return text;
}
public static void main(String[] args) {
List<Order> orders = new ArrayList<>(Arrays.asList(
new Order(1, "asha", 54700, "DELIVERED"),
new Order(7, "meera", 79800, "PREPARING"),
new Order(3, "meera", 21900, "CANCELLED")));
Collections.sort(orders, new Comparator<Order>() {
@Override public int compare(Order a, Order b) {
return Integer.compare(b.getTotalCents(), a.getTotalCents());
}
});
for (Order o : orders) {
System.out.println(o.getId() + " " + o.getCustomer() + " " + label(o.getStatus()));
}
}
}7 meera cooking
1 asha done
3 meera otherimport java.util.*;
public class NewStyle17 {
record Order(int id, String customer, int totalCents, String status) {}
static String label(String status) {
return switch (status) {
case "DELIVERED" -> "done";
case "PREPARING" -> "cooking";
default -> "other";
};
}
public static void main(String[] args) {
var orders = new ArrayList<>(List.of(
new Order(1, "asha", 54700, "DELIVERED"),
new Order(7, "meera", 79800, "PREPARING"),
new Order(3, "meera", 21900, "CANCELLED")));
orders.sort(Comparator.comparingInt(Order::totalCents).reversed());
for (var o : orders) {
System.out.println(o.id() + " " + o.customer() + " " + label(o.status()));
}
}
}7 meera cooking
1 asha done
3 meera otherSame output, 63 lines against 24. The shorter file is not clever. It uses five features that this section will introduce one by one: record (Java 16), var (10), List.of (9), a switch expression (14), and a method reference passed to Comparator (8). Every one of them is something you can read in a few seconds once you know it.
The timeline
Figure 21.2 shows all the releases from 8 to 27 as one tick each. Five of them are highlighted. Those are the LTS releases, the ones most companies actually run. Everything between two LTS releases is still real Java, and its features are all in the next LTS, but fewer production systems stop there.
Two facts in the figure are worth remembering. First, the gap between Java 8 and Java 9 was three and a half years, which is why Java 8 became the version everyone learned. Second, since Java 10 the rhythm is strict: March and September, no exceptions. A feature that misses a release does not wait years, it waits six months. That is why this chapter's cards are small and numerous.
Bridge: how to read a version card
After the compile proofs, each release gets a card with the same shape: two to four sentences on what the release was about, a table, and for the headline feature a side-by-side "before and after". The table has four columns.
| Column | What it holds | Example |
|---|---|---|
| Feature | The name of the language feature, API or tool. | Records |
| One-liner | One sentence on what it does for you, in plain words. The real code appears in the duo and in the cheat sheet in section 03. | A one-line declaration of an immutable data class. |
| Since | The first release where it is usable by default. | 16 |
| Status | final means it is a permanent part of Java. preview means it ships but is switched off unless you pass --enable-preview; it may still change or vanish. incubator is the same idea for a library module. | final |
The rule for "Since" is strict: it is the release where you can use the feature without any flag. Records were previews in Java 14 and 15, but their "Since" is 16. That is the number to put in a build file.
The compile-proof device
Reading that records arrived in Java 16 is easy to forget. Watching a compiler refuse them on 15 is hard to forget. So this chapter proves every headline feature with the same two commands.
javac --release 15 Record16.java # one release before: expect an error
javac --release 16 Record16.java # the release that added it: expect success
java Record16 # run the result--release N tells the compiler to behave exactly like a Java N compiler. It does two things at once. It limits the syntax to what Java N allowed, and it limits the class library to the classes and methods that existed in Java N. That is why a single JDK 25 can prove claims about Java 8, 9, 10 and so on.
Two details you will see in the output. First, --release 8 prints three "obsolete" warnings, because the JDK is nudging you away from targeting such an old release. They are real, so we keep them. Second, the error text is written by the new compiler about the old one, for example "records are not supported in -source 15". That wording is the compiler's, not ours.
A short word on the stack, because this chapter's whole method rests on it. The options below all answer the question "does this code work on Java N?", and the right one depends on what you have installed.
| Option | Pick it when | Cost or catch |
|---|---|---|
javac --release N on a newer JDK | You want a fast yes or no for syntax and library calls, and you have one modern JDK. | It does not run the code on Java N, so runtime behaviour differences (like the Java 17 reflection rule below) are not caught. |
| Install the old JDK and compile and run on it | You must see runtime behaviour or exact stack traces, as with InaccessibleObjectException. | You must install and manage several JDKs. This chapter uses JDK 8, 17, 21 and 25. |
-source N -target N instead of --release N | Almost never. It is the older flag pair. | It checks syntax but not the class library, so a call to List.of would compile and then fail at run time on Java 8. |
| Maven or Gradle toolchains | A team build that must be reproducible. | More setup. We come back to this in section 03. |
Use --release, never -source/-target alone. The difference is exactly the kind of bug you are trying to avoid: code that compiles on the build machine and breaks on the target. Here are the nine proofs, in release order.
The nine compile proofs
Proof: var arrived in Java 10
Java 10 lets the compiler work out a local variable's type, so you write var names = new ArrayList<String>(); instead of repeating the type.
import java.util.*;
public class Var10 {
public static void main(String[] args) {
var names = new ArrayList<String>();
names.add("asha");
names.add("ravi");
for (var n : names) {
System.out.println(n.toUpperCase());
}
}
}$ javac --release 9 Var10.java
Var10.java:5: warning: as of release 10, 'var' is a restricted type name and cannot be used for type declarations or as the element type of an array
var names = new ArrayList<String>();
^
Var10.java:8: warning: as of release 10, 'var' is a restricted type name and cannot be used for type declarations or as the element type of an array
for (var n : names) {
^
Var10.java:5: error: cannot find symbol
var names = new ArrayList<String>();
^
symbol: class var
location: class Var10
Var10.java:8: error: cannot find symbol
for (var n : names) {
^
symbol: class var
location: class Var10
2 errors
2 warnings
[exit 1]
$ javac --release 10 Var10.java
[exit 0]
$ java -cp out Var10
ASHA
RAVIBefore 10, var is not a keyword, so the compiler looks for a class called var and cannot find it. It even warns you that 10 will reserve the word.
Proof: List.of arrived in Java 9
Java 9 added factory methods that build small immutable lists, sets and maps in one line.
import java.util.*;
public class ListOf9 {
public static void main(String[] args) {
List<String> cities = List.of("Bengaluru", "Mysuru");
System.out.println(cities);
}
}$ javac --release 8 ListOf9.java
warning: [options] source value 8 is obsolete and will be removed in a future release
warning: [options] target value 8 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
ListOf9.java:5: error: cannot find symbol
List<String> cities = List.of("Bengaluru", "Mysuru");
^
symbol: method of(String,String)
location: interface List
1 error
3 warnings
[exit 1]
$ javac --release 9 ListOf9.java
[exit 0]
$ java -cp out ListOf9
[Bengaluru, Mysuru]The method simply does not exist in the Java 8 class library. This is an API error, not a syntax error.
Proof: String.repeat and isBlank arrived in Java 11
Java 11 added a handful of everyday string methods, among them repeat(n) and isBlank().
public class Strings11 {
public static void main(String[] args) {
System.out.println("=".repeat(12));
System.out.println(" ".isBlank());
}
}$ javac --release 10 Strings11.java
Strings11.java:3: error: cannot find symbol
System.out.println("=".repeat(12));
^
symbol: method repeat(int)
location: class String
Strings11.java:4: error: cannot find symbol
System.out.println(" ".isBlank());
^
symbol: method isBlank()
location: class String
2 errors
[exit 1]
$ javac --release 11 Strings11.java
[exit 0]
$ java -cp out Strings11
============
trueTwo missing methods, two errors. The language is the same; the class library is older.
Proof: switch expressions arrived in Java 14
Java 14 made switch something that produces a value, with -> arms and no fall-through.
public class Switch14 {
public static void main(String[] args) {
String status = "PREPARING";
int step = switch (status) {
case "PLACED" -> 1;
case "PREPARING" -> 2;
case "DELIVERED" -> 3;
default -> 0;
};
System.out.println(step);
}
}$ javac --release 13 Switch14.java
Switch14.java:4: error: switch expressions are not supported in -source 13
int step = switch (status) {
^
(use -source 14 or higher to enable switch expressions)
Switch14.java:5: error: switch rules are not supported in -source 13
case "PLACED" -> 1;
^
(use -source 14 or higher to enable switch rules)
2 errors
[exit 1]
$ javac --release 14 Switch14.java
[exit 0]
$ java -cp out Switch14
2The compiler refuses the new syntax and tells you which release enables it. On 12 and 13 the feature existed only as a preview, which needed --enable-preview, so it was off for normal builds.
Proof: text blocks arrived in Java 15
Java 15 added triple-quoted strings that span lines, so JSON and SQL stop needing \n and +.
public class TextBlock15 {
public static void main(String[] args) {
String json = """
{"order": 7,
"status": "DELIVERED"}
""";
System.out.print(json);
}
}$ javac --release 14 TextBlock15.java
TextBlock15.java:3: error: text blocks are not supported in -source 14
String json = """
^
(use -source 15 or higher to enable text blocks)
1 error
[exit 1]
$ javac --release 15 TextBlock15.java
[exit 0]
$ java -cp out TextBlock15
{"order": 7,
"status": "DELIVERED"}A syntax error again, with the helpful hint "use -source 15 or higher".
Proof: records arrived in Java 16
Java 16 added record, a one-line declaration of an immutable data class.
public class Record16 {
record Line(String item, int qty) {}
public static void main(String[] args) {
Line l = new Line("biryani", 2);
System.out.println(l);
}
}$ javac --release 15 Record16.java
Record16.java:2: error: records are not supported in -source 15
record Line(String item, int qty) {}
^
(use -source 16 or higher to enable records)
Record16.java:2: warning: 'record' may become a restricted type name in a future release and may be unusable for type declarations or as the element type of an array
record Line(String item, int qty) {}
^
1 error
1 warning
[exit 1]
$ javac --release 16 Record16.java
[exit 0]
$ java -cp out Record16
Line[item=biryani, qty=2]record is a new kind of declaration. The warning even says the word may become reserved.
Proof: instanceof patterns arrived in Java 16
Java 16 lets you test a type and name the cast result in one step: o instanceof String s.
public class Instanceof16 {
public static void main(String[] args) {
Object o = "biryani";
if (o instanceof String s && s.length() > 3) {
System.out.println(s.toUpperCase());
}
}
}$ javac --release 15 Instanceof16.java
Instanceof16.java:4: error: pattern matching in instanceof is not supported in -source 15
if (o instanceof String s && s.length() > 3) {
^
(use -source 16 or higher to enable pattern matching in instanceof)
1 error
[exit 1]
$ javac --release 16 Instanceof16.java
[exit 0]
$ java -cp out Instanceof16
BIRYANIThe compiler recognises the shape and names the feature it lacks.
Proof: Stream.toList() arrived in Java 16
Java 16 added toList() directly on Stream, so the common ending .collect(Collectors.toList()) shrinks.
import java.util.stream.Stream;
public class ToList16 {
public static void main(String[] args) {
var evens = Stream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).toList();
System.out.println(evens);
}
}$ javac --release 15 ToList16.java
ToList16.java:5: error: cannot find symbol
var evens = Stream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).toList();
^
symbol: method toList()
location: interface Stream<Integer>
1 error
[exit 1]
$ javac --release 16 ToList16.java
[exit 0]
$ java -cp out ToList16
[2, 4]An API error: Stream had no such method before 16.
Proof: sealed interfaces arrived in Java 17
Java 17 lets you say exactly which classes may implement an interface, using sealed and permits.
public class Sealed17 {
sealed interface Payment permits Card, Upi {}
record Card(String last4) implements Payment {}
record Upi(String handle) implements Payment {}
public static void main(String[] args) {
Payment p = new Upi("asha@bank");
System.out.println(p);
}
}$ javac --release 16 Sealed17.java
Sealed17.java:2: error: sealed classes are not supported in -source 16
sealed interface Payment permits Card, Upi {}
^
(use -source 17 or higher to enable sealed classes)
Sealed17.java:2: error: '{' expected
sealed interface Payment permits Card, Upi {}
^
2 errors
[exit 1]
$ javac --release 17 Sealed17.java
[exit 0]
$ java -cp out Sealed17
Upi[handle=asha@bank]Two errors for one cause. The second, '{' expected, is the parser being confused by the unknown word sealed, a good reminder that the first error is the one to read.
Nine features, nine real refusals. Keep this table as your memory aid. The "fails on" column is the last release without the feature.
| Feature | Fails on --release | Works on --release | Kind of error |
|---|---|---|---|
var | 9 | 10 | Syntax (unknown word) |
List.of | 8 | 9 | Library (missing method) |
String.repeat, isBlank | 10 | 11 | Library |
| Switch expression | 13 | 14 | Syntax |
| Text block | 14 | 15 | Syntax |
| Record | 15 | 16 | Syntax |
instanceof pattern | 15 | 16 | Syntax |
Stream.toList() | 15 | 16 | Library |
| Sealed interface | 16 | 17 | Syntax |
One more habit worth building from this table. When a build breaks after a Java upgrade, ask first whether the error is syntax or library. A syntax error points at the language level your build file sets. A missing method points at the JDK your build runs on, or at a --release that is too low.
Java 8 (March 2014, LTS): the release that changed how Java is written
Before Java 8, passing behaviour around meant writing a class, usually an anonymous one, with a method inside it. After Java 8, passing behaviour meant writing an arrow. That one change made a whole style of code, streams and fluent pipelines, practical.
Java 8 is also the longest card because it is the release most codebases are still shaped by. If you maintain a service that started before 2019, it is probably Java 8 in style even when it runs on a newer JDK.
The table lists what the release gave you. The two big items, lambdas and streams, have their own full sections later: lambdas and Optional and how a stream pipeline runs. Here the goal is only to recognise them and see the before and after.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Lambdas | A short anonymous function, written x -> x * 2, for any place that wants a single-method interface. | 8 | final |
| Method references | String::length names a method that already exists, used where a lambda would go. | 8 | final |
| Stream API | Describe a computation over a collection as a pipeline: filter, map, collect. | 8 | final |
| Default and static interface methods | An interface can carry method bodies. That is how List.sort could be added without breaking every class that implements List. | 8 | final |
| Optional | A box that holds a value or nothing, for return values that may be absent. | 8 | final |
| java.time | Immutable date and time classes (LocalDate, Instant, Duration) that replace Date and Calendar. | 8 | final |
| CompletableFuture | A future you can chain, combine and complete yourself. Section 11 builds it up. | 8 | final |
| New collection and map methods | getOrDefault, putIfAbsent, computeIfAbsent, merge, forEach on maps; removeIf on collections. | 8 | final |
| Concurrency helpers | LongAdder for counters many threads update, StampedLock for read-heavy locking, Arrays.parallelSort. | 8 | final |
| Metaspace replaces PermGen | Class metadata moved out of a fixed-size heap region, ending the old PermGen out-of-memory errors. | 8 (JVM) | final |
Three before-and-afters follow. Each left side is how the code was written through Java 7, and each is valid Java on 8 too, so you will meet them in old code. Every right side compiles with --release 8.
The first is sorting. A comparator is a tiny object that says which of two things comes first. In Java 7 you had to build one as an anonymous class, which is five lines for one idea.
Java 7 style
An anonymous class: a class with no name, created and used on the spot.
Collections.sort(list,
new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});Java 8
A method reference passed to Comparator.comparing. Same behaviour.
list.sort(
Comparator.comparing(String::length));The shift: the lambda carries the idea (compare by length), and Comparator.comparing removes the rest.
The second is a loop that filters and transforms. The loop shape is: make an empty result, walk the input, test each item, add the survivors. Streams name each of those steps so you can read the pipeline as a sentence.
Java 7 style
A loop with a temporary list and an if inside.
List<String> big = new ArrayList<>();
for (String x : list) {
if (x.length() > 3) {
big.add(x.toUpperCase());
}
}Java 8
A stream pipeline with three named steps.
List<String> big = list.stream()
.filter(x -> x.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());The shift: a stream states what you want (keep long words, upper-case them, collect them) and leaves the loop to the library.
The third is dates. The old Calendar class changes itself when you call add, counts months from zero, and cannot be shared safely between threads. LocalDate is immutable: every method returns a new date.
Java 7 style
Calendar plus Date: mutable, months start at zero.
Calendar c = Calendar.getInstance();
c.set(2026, Calendar.NOVEMBER, 28);
c.add(Calendar.DAY_OF_MONTH, 1);
Date next = c.getTime();Java 8
LocalDate: immutable, month 11 means November.
LocalDate next =
LocalDate.of(2026, 11, 28).plusDays(1);The shift: an immutable date object turns four mutable steps into one expression you can read left to right.
What did Java 8 not change? Checked exceptions still cannot be thrown from a lambda body unless the functional interface allows it, and there was still no var, no List.of and no records. The next releases fill those gaps one at a time. The Nashorn JavaScript engine also shipped in 8 and was removed again in Java 15; if you see ScriptEngineManager in old code, that is why it stops working.
Java 9 (September 2017): modules, JShell and the first small conveniences
Java 9 came three and a half years after Java 8 and carried one huge change for the JDK itself, the module system, plus a list of small additions that you will use every day. The small additions are the part to learn first.
If you remember one line from this card, remember List.of(...). Building an immutable list or map used to take four lines and a wrapper call.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Modules (JPMS) | A module-info.java file states which packages a bundle shows to others and which modules it needs. | 9 | final |
| JShell | An interactive prompt that evaluates Java one line at a time, handy for trying an API. | 9 | final |
| Collection factories | List.of, Set.of, Map.of, Map.entry: immutable collections in one line. | 9 | final |
| Private interface methods | Helper code inside an interface that implementers cannot see. | 9 | final |
| Stream additions | takeWhile, dropWhile, Stream.ofNullable, and Stream.iterate with a stop condition. | 9 | final |
| Optional additions | ifPresentOrElse, or, stream. | 9 | final |
| try-with-resources on a variable | try (r) { ... } works on an existing effectively final variable. | 9 | final |
| CompletableFuture timeouts | orTimeout and completeOnTimeout end the wait on a slow future. | 9 | final |
| Collector additions | Collectors.filtering and Collectors.flatMapping work inside a group. | 9 | final |
| Smaller items | InputStream.transferTo, ProcessHandle, the Flow API; G1 becomes the default garbage collector; compact strings. | 9 (JVM and API) | final |
Two duos cover the changes you will meet most often in application code. First, maps and lists with fixed contents. The Java 8 way builds a mutable map, fills it, then wraps it so nobody can change it.
Java 8
A mutable map, filled, then wrapped as read-only.
Map<String, Integer> m = new HashMap<>();
m.put("asha", 3);
m.put("ravi", 2);
m = Collections.unmodifiableMap(m);Java 9
Map.of: immutable from birth.
Map<String, Integer> m =
Map.of("asha", 3, "ravi", 2);The shift: Map.of states the contents once and refuses changes. It also refuses null keys and values, which a HashMap would accept.
Second, try-with-resources. A resource is something that must be closed, like a file reader. Before Java 9 you had to copy an existing variable into a new one inside the parentheses. In Java 9 you can name the variable itself, as long as nothing reassigns it.
Java 8
A second variable, r2, only to satisfy the syntax.
BufferedReader r = open();
try (BufferedReader r2 = r) {
r2.readLine();
}Java 9
The existing variable r is used directly.
BufferedReader r = open();
try (r) {
r.readLine();
}The shift: if the variable is effectively final (never reassigned), you can use it directly in the try (...) header.
Bridge: modules, one level down
A module is a named bundle of packages with a short file at its root, module-info.java. That file says two things: which other modules this one needs (requires), and which of its own packages other modules may use (exports). Everything else in the bundle is hidden from outsiders, even classes marked public. Think of it as a third level of access control above public.
// illustrative
module com.quickbite.orders {
requires java.sql; // I need the JDBC module
exports com.quickbite.orders.api; // outsiders may use this package only
}Most application teams never write a module-info.java, and that is fine. The part of Java 9 that mattered for everybody was that the JDK itself was split into modules (java.base, java.sql, java.net.http and so on).
That allowed smaller runtimes (the jlink tool builds one with only the modules you need) and, more painfully, it allowed the JDK to hide its own internals. Application code that stays on the plain classpath runs as one big "unnamed module" and behaves as before, so Spring, Hibernate and most libraries just kept working.
Two pains remain for people who do use modules. The first is the split package: if two jars both contain a package with the same name, the module system refuses to start. The second is encapsulation. Libraries that reached into JDK internals with reflection were allowed to keep doing so through Java 15 with a warning, and then were blocked. You will see that block run for real in the Java 17 card below.
JShell: try a line without a class
JShell is the other headline of Java 9. It reads one line, evaluates it, and prints the result. There is no class and no main. That makes it the fastest way to test whether a method does what you think. The next session feeds four lines to the real jshell tool from JDK 25.
var orders = List.of("o1", "o2", "o3")
orders.size()
orders.stream().map(String::toUpperCase).toList()
"abc".repeat(2)
/exit$ jshell
| Welcome to JShell -- Version 25.0.5.1
jshell> var orders = List.of("o1", "o2", "o3")
orders ==> [o1, o2, o3]
jshell> orders.size()
$2 ==> 3
jshell> orders.stream().map(String::toUpperCase).toList()
$3 ==> [O1, O2, O3]
jshell> "abc".repeat(2)
$4 ==> "abcabc"
jshell> /exitNotice the var orders = ... on the first line: JShell on Java 25 accepts var, List.of, a stream pipeline ending in toList(), and String.repeat, all features from different releases of this section. You can paste any one-liner from the cheat sheet in section 03 into JShell to see it work.
Java 10 (March 2018): var, and the six-month rhythm begins
Java 10 is small, and it is the first release on the new six-month schedule. Its famous feature is var, which lets the compiler infer the type of a local variable.
var is not dynamic typing. The type is still fixed at compile time; you just stop writing it twice.
| Feature | One-liner | Since | Status |
|---|---|---|---|
var | The compiler infers a local variable's type from the right-hand side. | 10 | final |
| Copy factories | List.copyOf, Set.copyOf, Map.copyOf make an immutable copy you can hand out safely. | 10 | final |
| Unmodifiable collectors | Collectors.toUnmodifiableList, toUnmodifiableSet, toUnmodifiableMap. | 10 | final |
Optional.orElseThrow() | The no-argument form: get the value or throw NoSuchElementException. It reads better than get(). | 10 | final |
| Six-month cadence | A new feature release every March and September, starting here. | 10 (process) | final |
The duo shows the typical win. When the type on the right is long, repeating it on the left adds nothing for the reader. With var the long name is written once.
Java 9
The type repeated on both sides, and again in the loop.
Map<String, List<String>> byCity =
new HashMap<>();
for (Map.Entry<String, List<String>> e
: byCity.entrySet()) {
System.out.println(e.getKey());
}Java 10
var for the map and for the loop variable.
var byCity =
new HashMap<String, List<String>>();
for (var e : byCity.entrySet()) {
System.out.println(e.getKey());
}The shift: write the type once, on the side where it is visible. The variable is still a HashMap<String, List<String>>.
var has limits, and the compiler enforces them. It works only for local variables, not fields, parameters or return types. The right-hand side must show the type. The next program breaks that last rule on purpose.
import java.util.*;
public class VarTrap {
public static void main(String[] args) {
var names = new ArrayList<>(); // no type on either side
names.add("asha");
String first = names.get(0);
System.out.println(first);
}
}$ javac --release 17 VarTrap.java
VarTrap.java:7: error: incompatible types: Object cannot be converted to String
String first = names.get(0);
^
1 error
[exit 1]new ArrayList<>() with an empty diamond and no variable type gives the compiler nothing to infer from, so it picks ArrayList<Object>. The error appears on a later line, far from the cause. Say the type on one side or the other and the bug disappears.
- Works:
varwhen the right side names the type (new HashMap<String, Integer>(), a constructor call, a clear factory method such asList.of(1, 2, 3)). - Fails:
var data = load();where nobody can tell whatloadreturns, andvarwith an empty diamond. Alsovarfor numbers when the width matters:var x = 1is anint, which may not be what you meant. - Interview takeaway: "var is local type inference. It removes repetition, never information. If a reader cannot see the type from the line, I write the type."
Java 11 (September 2018, LTS): the standard HTTP client and the first useful String methods
Java 11 is the first LTS after Java 8, so it is where many teams jumped. The move from 8 to 11 is mostly about things that were removed (the Java EE and CORBA modules), plus a set of new conveniences.
The two to remember are the standard HttpClient, which replaced a very old API, and the ability to run a single source file with no separate compile step.
| Feature | One-liner | Since | Status |
|---|---|---|---|
HttpClient | A modern HTTP client in java.net.http: HTTP/2, async calls, a builder for requests. | 11 | final |
| String methods | isBlank, lines, strip, stripLeading, stripTrailing, repeat. | 11 | final |
| File shortcuts | Files.readString and Files.writeString read and write a whole file as text. | 11 | final |
var in lambda parameters | (var x, var y) -> x + y, mainly so you can add annotations to the parameters. | 11 | final |
| Run a source file directly | java Hello.java compiles in memory and runs. No javac step. | 11 | final |
| Small API additions | Optional.isEmpty, Predicate.not, Collection.toArray(IntFunction). | 11 | final |
| Garbage collectors | ZGC (experimental) and the do-nothing Epsilon collector arrive; JDK Flight Recorder is open-sourced. | 11 (JVM) | final |
| Removals and security | Java EE and CORBA modules removed from the JDK (code using JAXB needs a library); TLS 1.3 supported. | 11 (JVM) | final |
The first duo is the file shortcut. Reading a text file as a String took two lines and a charset name. Now it takes one.
Java 10
Read bytes, then decode them yourself.
byte[] b = Files.readAllBytes(p);
String text =
new String(b, StandardCharsets.UTF_8);Java 11
One call that returns the text.
String text = Files.readString(p);The shift: when a whole file fits in memory, Files.readString is the whole job. It uses UTF-8 unless you pass another charset.
The second duo is HTTP. Java's old HttpURLConnection is a mutable connection object from the 1990s: you configure it with setters, then read the response code and stream by hand. The new client is built from a request object and a client object, and it can also send requests asynchronously.
Java 10
HttpURLConnection: a stateful connection object.
URL u = new URL("https://x.io/menu");
HttpURLConnection c =
(HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
int code = c.getResponseCode();Java 11
HttpClient and HttpRequest: built, then sent.
var client = HttpClient.newHttpClient();
var req = HttpRequest
.newBuilder(URI.create("https://x.io/menu"))
.build();
var res = client.send(req,
HttpResponse.BodyHandlers.ofString());The shift: build an immutable request, send it through a reusable client, get a response object back.
HttpClient has no external dependency, so a small tool or a health check no longer needs a library. Java 26 added HTTP/3 to this same client; you will see that in the next section.
Run a source file straight away
Before Java 11, even "hello world" needed javac first and a .class file second. From Java 11 the java launcher accepts a .java file, compiles it in memory and runs it. That is what the later chapters of this course use for every demo. Here is the proof on JDK 8 and JDK 17.
public class Hello11 {
public static void main(String[] args) {
System.out.println("run straight from source");
}
}$ java Hello11.java # JDK 8
Error: Could not find or load main class Hello11.java
$ java Hello11.java # JDK 17
run straight from sourceJDK 8 treats Hello11.java as a class name and cannot find it. JDK 17 compiles the file and runs it. This is the feature that makes a Java file feel like a script, and Java 22 and Java 25 would later extend it (more files, then even a file with no class).
Java 12 and 13 (March and September 2019): the first previews
These two releases are small in final features and important in process. They are where Java first shipped a feature in preview, so that real programs could try it and report problems before it became permanent.
Switch expressions arrived as a preview in 12 and changed in 13. Text blocks arrived as a preview in 13. Neither is final yet in this card: switch expressions became final in Java 14 and text blocks in Java 15, and the compile proofs above show those releases.
| Feature | One-liner | Since | Status |
|---|---|---|---|
Collectors.teeing | Run two collectors over the same stream in one pass and merge their results. | 12 | final |
String.indent, String.transform | Indent every line by n spaces; pipe a string through a function. | 12 | final |
Files.mismatch | The position of the first byte where two files differ, or -1 if they are equal. | 12 | final |
CompactNumberFormat | Formats 1,500 as "1.5K" and similar short forms. | 12 | final |
| Switch expressions | Preview in 12 and 13; final in 14. | 14 | preview in 12, 13 |
Text blocks and yield | Preview in 13; text blocks final in 15, yield in switch final in 14. | 15 | preview in 13 |
| Shenandoah GC | A low-pause garbage collector, experimental here. | 12 (JVM) | experimental |
teeing is the one final API of the pair that changes how you write stream code. Before it, getting both a count and a joined string from one list meant walking the list twice or writing a custom collector. teeing takes two collectors and a function that combines their two results.
Java 11
Two separate passes over the list.
long count = list.stream().count();
String all = list.stream()
.collect(Collectors.joining(","));
String r = count + ":" + all;Java 12
Collectors.teeing: both collectors in one pass.
String r = list.stream().collect(
Collectors.teeing(
Collectors.counting(),
Collectors.joining(","),
(c, j) -> c + ":" + j));The shift: two answers from one walk, with no temporary variables outside the pipeline. The name comes from the tee pipe fitting that splits a flow in two.
A preview feature is a promise with a catch. You can use it if you pass --enable-preview to both the compiler and the runtime, and the class files you build will refuse to run without that flag. The feature may still change. Section 03 shows the whole life cycle of previews as a picture (Fig. 21.3) and runs a preview feature for real.
Java 14 (March 2020): switch becomes an expression, and NullPointerException learns to speak
Java 14 finished the first big language change since lambdas. The switch statement became a switch expression: it produces a value, uses arrows, and cannot fall through by accident.
It also made the most common runtime error far easier to diagnose. A NullPointerException now tells you which variable or method result was null.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Switch expressions | switch that produces a value, with -> arms and yield for blocks. | 14 | final |
| Helpful NullPointerExceptions | The message names the null variable or call, for example "because the return value of Map.get(Object) is null". | 14 (on by default from 15) | final |
| Records | Preview in 14 and 15, final in 16. | 16 | preview |
Pattern matching for instanceof | Preview in 14 and 15, final in 16. | 16 | preview |
The old switch statement had two traps. If you forget break, execution falls into the next case. And because it is a statement, it cannot return a value, so you declare a variable first and assign it in each branch. The expression form removes both.
Java 13
Old switch: a variable declared first, break after each case.
int step;
switch (status) {
case "PLACED": step = 1; break;
case "PREPARING": step = 2; break;
default: step = 0;
}Java 14
Switch expression: arrows, no fall-through, one assignment.
int step = switch (status) {
case "PLACED" -> 1;
case "PREPARING" -> 2;
default -> 0;
};The shift: an arrow arm runs only its own code, and the whole switch gives back a value, so the variable is assigned exactly once.
A bonus: because a switch expression must produce a value for every input, the compiler insists on a default arm or, for enums and sealed types, on covering every case. A missing case becomes a compile error instead of a silent "nothing happens".
Helpful NullPointerExceptions, run on two JDKs
Everyone has met this error. In Java 8 the message was empty: you got the line number and had to guess which of five expressions on that line was null. The next program calls get for a customer who is not in the map and then calls a method on the missing value.
import java.util.*;
public class HelpfulNpe {
public static void main(String[] args) {
Map<String, String> cityByCustomer = new HashMap<>();
cityByCustomer.put("asha", "Bengaluru");
System.out.println(cityByCustomer.get("ravi").toUpperCase());
}
}$ java HelpfulNpe # JDK 8
Exception in thread "main" java.lang.NullPointerException
at HelpfulNpe.main(HelpfulNpe.java:7)
$ java HelpfulNpe # JDK 17
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because the return value of "java.util.Map.get(Object)" is null
at HelpfulNpe.main(HelpfulNpe.java:7)Same bytecode, two different messages. JDK 17 says what was null ("the return value of Map.get(Object)") and what you tried to do with it (call toUpperCase). For local variables it also names the variable, if the code was compiled with -g. I have only run this on 8 and 17 on this machine. Java 14 had the feature behind a flag, and it became the default in Java 15.
Java 15 (September 2020): text blocks, and more previews
Java 15 finishes text blocks: multi-line strings between triple quotes. If you have ever built JSON, SQL or HTML in a Java string, this is the release that removes the \n, the + and the escaped quotes.
It also adds formatted on strings and introduces sealed classes as a preview, to be finished in Java 17.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Text blocks | A string that spans lines between """ delimiters. | 15 | final |
String.formatted | "Order %d".formatted(7) is String.format as an instance method. | 15 | final |
| Sealed classes | Preview in 15 and 16, final in 17. | 17 | preview |
| Hidden classes | A JVM feature for frameworks that generate classes at run time; lambdas use it internally. | 15 (JVM) | final |
| ZGC and Shenandoah | Both become production-ready collectors. | 15 (JVM) | final |
| Nashorn removed | The JavaScript engine from Java 8 is gone. | 15 (removal) | final |
Java 14
Concatenation, \n and escaped quotes.
String json = "{\n"
+ " \"order\": 7,\n"
+ " \"status\": \"DELIVERED\"\n"
+ "}\n";Java 15
A text block: what you see is what you get.
String json = """
{
"order": 7,
"status": "DELIVERED"
}
""";The shift: the text block shows the shape of the data on the page. The compiler removes the common indentation.
How does the compiler decide how much leading space to remove? It looks at every content line and at the closing """ line and removes the smallest common indent. So the position of the closing delimiter is a control: put it further left and the text keeps some indent, put it level with the text and none stays. Look back at the proof program, TextBlock15.java: the content is indented 12 spaces and so is the closing delimiter, so the printed lines start at column zero.
Java 16 (March 2021): records, instanceof patterns, and the end of casual reflection
Java 16 is the release where the "less ceremony" features land together. Records give you the data class in one line. Pattern matching for instanceof removes the cast after a type test. Stream.toList() shortens the most common ending of a pipeline.
It also made a quiet change that broke many applications a year later: JDK internals are strongly encapsulated by default. The Java 17 card shows the break running.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Records | A one-line immutable data class. The compiler writes the constructor, accessors, equals, hashCode and toString. | 16 | final |
instanceof patterns | o instanceof String s tests, casts and names in one step. | 16 | final |
Stream.toList() | Ends a pipeline with an unmodifiable list, replacing collect(Collectors.toList()). | 16 | final |
Stream.mapMulti | Emit zero, one or many outputs per input, without creating a stream per element. | 16 | final |
| jpackage | Builds a native installer (.deb, .msi, .dmg) from a Java application. | 16 (tool) | final |
| Strong encapsulation (JEP 396) | Reflection into JDK internal packages is denied by default (the old --illegal-access flag is removed a release later, in 17). | 16 (JVM) | final |
Records first. A record declares its fields in the header, and everything else is generated. It is meant for data that is exactly what it looks like: a line of an order, a point, a pair. A record cannot extend another class and its fields are final. Left is the Java 15 class with the code you used to write by hand.
Java 15
A hand-written immutable class (shown trimmed).
final class Line {
private final String item;
private final int qty;
Line(String item, int qty) {
this.item = item;
this.qty = qty;
}
String item() { return item; }
int qty() { return qty; }
// plus equals, hashCode, toString
}Java 16
A record: one line.
record Line(String item, int qty) {}The shift: a record is a promise that the object is nothing but its fields. That promise is why the compiler can safely write the rest.
Second, instanceof. The old form tests the type, then casts to the same type on the next line. That repeats the type name three times and invites mistakes if you cast to the wrong type. The new form declares the variable inside the test.
Java 15
Test, then cast on the next line.
if (o instanceof String) {
String t = (String) o;
System.out.println(t.length());
}Java 16
Test and name in one expression.
if (o instanceof String t) {
System.out.println(t.length());
}The shift: the variable t exists only where the test is true, so there is no way to use it unsafely.
Third, Stream.toList(). It returns a list you cannot change: calling add on it throws UnsupportedOperationException. The older collect(Collectors.toList()) gave an ArrayList in practice, though the documentation made no promise. Prefer toList() unless some later code must modify the list. The streams section runs this difference for real.
Java 17 (September 2021, LTS): sealed types, and the day reflection stopped working
Java 17 is the LTS that moved most companies off Java 11. It finishes sealed classes, which let you list exactly which types may extend one, and it removes the last way around the strong encapsulation that Java 16 started.
The language features are pleasant. The encapsulation change is the one that causes upgrade incidents, so this card spends more time on it.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Sealed classes and interfaces | sealed ... permits A, B lists every allowed subtype, so the compiler knows the full set. | 17 | final |
Pattern matching for switch | Preview in 17 to 20, final in 21. | 21 | preview |
| Strong encapsulation (JEP 403) | --illegal-access is gone; reflection into JDK internals fails unless you open the package explicitly. | 17 (JVM) | final |
RandomGenerator | A common interface for random number generators, with newer algorithms such as L64X128MixRandom. | 17 | final |
HexFormat | Hex strings to bytes and back. | 17 | final |
| Security Manager deprecated for removal | The old sandbox is on the way out; Java 24 disabled it permanently. | 17 (deprecation) | final |
Java 16
An open interface: anybody may add another implementation.
interface Payment {}
record Card(String last4)
implements Payment {}
record Upi(String handle)
implements Payment {}
// anyone may add: record Cash() ...Java 17
A sealed interface: the full list is in the declaration.
sealed interface Payment
permits Card, Upi {}
record Card(String last4)
implements Payment {}
record Upi(String handle)
implements Payment {}The shift: with sealed, a reader and the compiler both see that these two classes are the only payments there will ever be.
Sealed types matter most when paired with switch. If every subtype is known, a switch over them needs no default, and adding a new subtype later turns every incomplete switch into a compile error. That pairing becomes final in Java 21 and is shown in the opening program of section 03.
Bridge: strong encapsulation, one level down
Inside the JDK, many classes keep private fields that libraries once read with reflection: String.value, parts of sun.misc.Unsafe, internals of java.util. Reflection could call setAccessible(true) on any private field and read it. Java 9 started a long migration: first a warning (9 to 15), then denial by default (16), then removal of the switch that allowed it (17).
The next program is the smallest possible example. It asks the JDK's String class for its private value field and tries to open it. On JDK 8 this just works. On JDK 17 it fails with a new exception, InaccessibleObjectException, whose message names the module and the package that is closed.
import java.lang.reflect.Array;
import java.lang.reflect.Field;
public class PeekInside {
public static void main(String[] args) throws Exception {
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
Object raw = f.get("hi");
System.out.println("inside String: " + raw.getClass().getSimpleName()
+ " of length " + Array.getLength(raw));
}
}$ java -version # JDK 8
openjdk version "1.8.0_514"
$ java PeekInside
inside String: char[] of length 2
$ java -version # JDK 17
openjdk version "17.0.21.1" 2026-11-17
$ java PeekInside
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module @70ffb6f
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
$ java --add-opens java.base/java.lang=ALL-UNNAMED PeekInside
inside String: byte[] of length 2What you see: on JDK 8 the field is a char[] of length 2 (compact strings arrived in Java 9, so on 17 and later the same field is a byte[], which the last run confirms). On JDK 17 the call to setAccessible throws, and the message says exactly which module (java.base) does not open which package (java.lang) to which module (the unnamed module that holds your classpath code).
The message is also the recipe for the bandage. The command-line flag --add-opens java.base/java.lang=ALL-UNNAMED opens that package to all classpath code, and the last run prints byte[] of length 2. You usually set it through JAVA_TOOL_OPTIONS, a Maven Surefire argLine, or a line in the container's start command.
The fix: the flag is a bandage, not a repair. The real fix is one of three things: stop using the internal field and call the public method instead (here, getBytes), upgrade the library that reaches in (Mockito, Lombok, Hibernate, Jackson modules and older Spring versions all had releases for this), or replace the library. Use --add-opens to get a build green while you do that, and write down the reason next to it.
A last point for upgrade planning. The failure appears at run time, not at compile time, which is why --release 17 compile proofs cannot catch it. You only find out by running the code on a 17 JDK, ideally with the test suite. Treat "upgrade the JDK in CI first" as a rule for any move from 8 or 11.
03 · Java 18 to 27Java 18 to 27, and the One-Liner Cheat Sheet
The last ten releases changed the shape of a Java file more than the previous ten. A whole service can now fit on one screen, and concurrency stopped needing a thread pool for most blocking work. This section shows what an upgrade from 21 to 25 gives you, release by release, and ends with a cheat sheet of 87 one-liners you can paste into JShell.
QuickBite's platform team runs Java 21. A new engineer asks why every small service starts with a class, a main method with a string array nobody uses, ten imports, and a thread pool configured by hand. Nobody has a good answer. They try the same service on Java 25 and it shrinks to 25 lines.
Here is that service. It models three order events (placed, delivered, cancelled), describes each one in a switch, and runs the three descriptions at the same time on virtual threads. It uses a compact source file, one module import, records, a sealed interface, record patterns, an unnamed _, and a virtual-thread executor. You do not need to understand every line yet; each of those ideas has its own card below.
import module java.base;
sealed interface Event permits Placed, Delivered, Cancelled {}
record Placed(int orderId, int totalCents) implements Event {}
record Delivered(int orderId, String rider) implements Event {}
record Cancelled(int orderId, String reason) implements Event {}
String describe(Event e) {
return switch (e) {
case Placed(int id, int cents) -> "order " + id + " placed, ₹" + cents / 100.0;
case Delivered(int id, _) -> "order " + id + " delivered";
case Cancelled(int id, String why) -> "order " + id + " cancelled: " + why;
};
}
void main() throws Exception {
List<Event> events = List.of(
new Placed(1, 54700), new Delivered(1, "kiran"), new Cancelled(3, "out of stock"));
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
var results = events.stream().map(e -> pool.submit(() -> describe(e))).toList();
for (var f : results) {
IO.println(f.get());
}
}
}Make the invisible visible: the program run on JDK 25, then the very same file compiled with --release 21. The compiler lists everything that does not exist yet in Java 21.
$ java QuickBiteSvc.java # JDK 25
order 1 placed, ₹547.0
order 1 delivered
order 3 cancelled: out of stock
$ javac --release 21 QuickBiteSvc.java
QuickBiteSvc.java:1: error: module imports are not supported in -source 21
import module java.base;
^
(use -source 25 or higher to enable module imports)
QuickBiteSvc.java:11: error: unnamed variables are not supported in -source 21
case Delivered(int id, _) -> "order " + id + " delivered";
^
(use -source 22 or higher to enable unnamed variables)
QuickBiteSvc.java:8: error: implicitly declared classes are not supported in -source 21
String describe(Event e) {
^
(use -source 25 or higher to enable implicitly declared classes)
3 errors
[exit 1]Three errors, three features. The module import and the file with no class (implicitly declared classes) arrived in Java 25. The _ in the pattern arrived in Java 22. The sealed interface, the records, the switch with record patterns and the virtual-thread executor are all already fine on Java 21, so they produced no errors. That is the "what you get by upgrading 21 to 25" story in one compile.
Now the cards. Quiet releases are combined (18; 19 and 20), and each loud release gets its own. Every compile proof is a real run, saved with its output under code/e21-modern-java/A/.
Java 18 (March 2022): UTF-8 everywhere, and a web server in one command
Java 18 is a quiet release with one change that fixes a whole class of "works on my machine" bugs: the default character set is now UTF-8 on every platform.
It also added a tiny built-in file server for demos and testing.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| UTF-8 by default | Charset.defaultCharset() is UTF-8 on every operating system and locale. | 18 | final |
jwebserver | A command-line tool that serves a folder over HTTP, for prototypes and tests. | 18 (tool) | final |
@snippet in Javadoc | Code samples in documentation that are real, compilable files. | 18 (tool) | final |
| Finalization deprecated for removal | finalize() methods are on their way out; use try-with-resources or Cleaner. | 18 (deprecation) | final |
Why UTF-8 matters: before Java 18, "the default charset" meant whatever the operating system said. A file written on a developer's Linux laptop and read in a Windows container could turn "₹" into garbage. The next program prints the default and is run twice with the locale forced to the basic C setting, once on JDK 17 and once on JDK 25.
import java.nio.charset.Charset;
public class DefaultCharset {
public static void main(String[] args) {
System.out.println("default charset: " + Charset.defaultCharset());
}
}$ LC_ALL=C java DefaultCharset.java # JDK 17
default charset: US-ASCII
$ LC_ALL=C java DefaultCharset.java # JDK 25
default charset: UTF-8JDK 17 follows the environment and reports US-ASCII, which cannot hold "₹". JDK 25 reports UTF-8 no matter what. If your code still passes a charset explicitly, nothing changes. If it relied on the default, the new behaviour is almost always the better one, and you can restore the old behaviour with -Dfile.encoding=COMPAT when you must.
jwebserver is the other visible tool. One command serves the current folder. The run below starts it on a port, fetches a page with curl, and shows the access line the server logged. It is meant for demos, not production: it serves static files only.
$ jwebserver -p 8099 -b 127.0.0.1 &
$ curl -s http://127.0.0.1:8099/
<h1>QuickBite menu</h1>Serving /home/iam100god/Desktop/AI_COURSE/code/e21-modern-java/A/modern/web and subdirectories on 127.0.0.1 port 8099
URL http://127.0.0.1:8099/
127.0.0.1 - - [01/Dec/2026:23:08:59 +0530] "GET / HTTP/1.1" 200 -Java 19 and 20 (September 2022, March 2023): virtual threads and patterns arrive as previews
These two releases are mostly previews: virtual threads, record patterns, structured concurrency (as an incubator module) and scoped values (also incubator). They matter because they are the first time you could try the ideas that became final in Java 21.
One final change from Java 19 is easy to miss and is worth a compile proof: ExecutorService became AutoCloseable, so try-with-resources can shut a pool down.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Virtual threads | Cheap threads managed by the JVM. Preview in 19 and 20, final in 21. | 21 | preview |
| Record patterns | Take a record apart inside instanceof and switch. Preview in 19 and 20, final in 21. | 21 | preview |
| Structured concurrency | Treat a group of subtasks as one unit. Incubator in 19 and 20, preview from 21, still preview in 27. | not yet | incubator, then preview |
| Scoped values | A safer cousin of ThreadLocal. Incubator in 20, preview in 21 to 24, final in 25. | 25 | incubator |
ExecutorService is AutoCloseable | try-with-resources shuts the pool down and waits for tasks. | 19 | final |
Thread.sleep(Duration) | Sleep for a Duration instead of a number of milliseconds. | 19 | final |
The pool is the practical change. For ten years the safe way to use a thread pool was a try/finally with shutdown() in the finally. People forgot the finally, or forgot to wait, and threads kept the JVM alive. In 19, close() does the whole job.
Java 18
try/finally with a manual shutdown().
ExecutorService ex =
Executors.newFixedThreadPool(4);
try {
ex.submit(() -> fetchMenu());
} finally {
ex.shutdown();
}Java 19
try-with-resources on the executor.
try (var ex =
Executors.newFixedThreadPool(4)) {
ex.submit(() -> fetchMenu());
}The shift: closing the pool is now the language's job: leaving the try block calls close(), which stops accepting tasks and waits for the running ones.
Here is the compile proof for it. On --release 18 the compiler says ExecutorService cannot be converted to AutoCloseable. On --release 19 it compiles and prints 42.
import java.util.concurrent.*;
public class Exec19 {
public static void main(String[] args) throws Exception {
try (ExecutorService ex = Executors.newFixedThreadPool(2)) {
Future<Integer> f = ex.submit(() -> 6 * 7);
System.out.println(f.get());
}
}
}$ javac --release 18 Exec19.java
Exec19.java:5: error: incompatible types: try-with-resources not applicable to variable type
try (ExecutorService ex = Executors.newFixedThreadPool(2)) {
^
(ExecutorService cannot be converted to AutoCloseable)
1 error
[exit 1]
$ javac --release 19 Exec19.java
[exit 0]
$ java -cp out Exec19
42This one is a library change, not a syntax change: the class ExecutorService itself gained a super-interface. The same code on Java 18 is a type error, which is exactly how the compiler says "this class did not have close before".
Java 21 (September 2023, LTS): virtual threads, patterns and sequenced collections
Java 21 is the most important release since 17 for application code. Virtual threads become final, pattern matching for switch and record patterns become final, and collections finally get getFirst, getLast and reversed.
If your company is on 17 and wondering why to move, this release is the answer. If it is on 21, most of what follows is already yours.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Virtual threads | Threads so cheap that you can create one per task. Section 12 builds them up. | 21 | final |
| Sequenced collections | getFirst, getLast, addFirst, addLast, reversed on lists, deques and ordered sets and maps. | 21 | final |
| Record patterns | case Card(String last4) takes a record apart inside a switch or instanceof. | 21 | final |
Pattern matching for switch | switch on the type of an object, with guards (when) and case null. | 21 | final |
| Generational ZGC | ZGC splits young and old objects, cutting memory use and CPU. | 21 (JVM) | final |
| Small API additions | Math.clamp, StringBuilder.repeat, Character.isEmoji. | 21 | final |
| Previews | Unnamed classes and instance main, unnamed patterns and variables, structured concurrency, scoped values, and string templates (those were later withdrawn and never shipped). | see text | preview |
Sequenced collections solve a small, annoying problem. A List has a first and a last element, but there was never one way to ask for them. For a list you wrote list.get(list.size() - 1). For a Deque the method was peekLast. For a LinkedHashSet there was no method at all. Java 21 adds one family of methods to all of them.
Java 20
Index arithmetic to get the last element; copy and reverse.
String last = list.get(list.size() - 1);
List<String> rev = new ArrayList<>(list);
Collections.reverse(rev);Java 21
getLast() and reversed(): a view, with no copy.
String last = list.getLast();
List<String> rev = list.reversed();The shift: the new methods exist on every collection that has a defined order, so you stop remembering which class spells it which way.
import java.util.*;
public class Sequenced21 {
public static void main(String[] args) {
List<String> orders = new ArrayList<>(List.of("o1", "o2", "o3"));
System.out.println(orders.getFirst() + " " + orders.getLast());
System.out.println(orders.reversed());
}
}$ javac --release 20 Sequenced21.java
Sequenced21.java:6: error: cannot find symbol
System.out.println(orders.getFirst() + " " + orders.getLast());
^
symbol: method getFirst()
location: variable orders of type List<String>
Sequenced21.java:6: error: cannot find symbol
System.out.println(orders.getFirst() + " " + orders.getLast());
^
symbol: method getLast()
location: variable orders of type List<String>
Sequenced21.java:7: error: cannot find symbol
System.out.println(orders.reversed());
^
symbol: method reversed()
location: variable orders of type List<String>
3 errors
[exit 1]
$ javac --release 21 Sequenced21.java
[exit 0]
$ java -cp out Sequenced21
o1 o3
[o3, o2, o1]Three missing methods on --release 20, one clean compile on --release 21. Note that reversed() gives you a view of the same list in the opposite order. It does not copy.
The second big change is pattern matching for switch. A switch over the type of an object replaces a chain of instanceof tests. The compiler checks that every case is handled when the type is sealed, and a when guard adds a condition to a case.
Java 20
An if/else if chain of instanceof tests.
String r;
if (o instanceof Integer i && i > 9) {
r = "big " + i;
} else if (o instanceof Integer i) {
r = "int " + i;
} else if (o instanceof String t) {
r = t;
} else {
r = "?";
}Java 21
A switch over the type, with when guards.
String r = switch (o) {
case Integer i when i > 9 -> "big " + i;
case Integer i -> "int " + i;
case String t -> t;
default -> "?";
};The shift: one switch expression, each arm names the type and the guard, and the compiler forbids forgetting a case in sealed hierarchies.
Add record patterns and you can take an object apart in the same step. The proof program below switches over a sealed Pay type and extracts the field out of each record in the case line itself.
public class RecordPattern21 {
sealed interface Pay permits Card, Upi {}
record Card(String last4) implements Pay {}
record Upi(String handle) implements Pay {}
static String describe(Pay p) {
return switch (p) {
case Card(String last4) -> "card ending " + last4;
case Upi(String handle) -> "UPI " + handle;
};
}
public static void main(String[] args) {
System.out.println(describe(new Card("4242")));
}
}$ javac --release 20 RecordPattern21.java
RecordPattern21.java:8: error: patterns in switch statements are not supported in -source 20
case Card(String last4) -> "card ending " + last4;
^
(use -source 21 or higher to enable patterns in switch statements)
RecordPattern21.java:8: error: deconstruction patterns are not supported in -source 20
case Card(String last4) -> "card ending " + last4;
^
(use -source 21 or higher to enable deconstruction patterns)
2 errors
[exit 1]
$ javac --release 21 RecordPattern21.java
[exit 0]
$ java -cp out RecordPattern21
card ending 4242On --release 20 the compiler rejects both halves, patterns in switch and deconstruction patterns, because both became final in 21.
The third big change is virtual threads. The duo below shows what you change in code: nothing but the factory. The difference is in what happens when 10,000 tasks each wait on the network, which section 12 measures.
Platform threads
A pool of 200 platform threads: at most 200 tasks wait at once.
try (var ex =
Executors.newFixedThreadPool(200)) {
ex.submit(() -> fetchMenu());
}Virtual threads
One virtual thread per task: thousands can wait at once.
try (var ex = Executors
.newVirtualThreadPerTaskExecutor()) {
ex.submit(() -> fetchMenu());
}The shift: a virtual thread is cheap enough to create for every task, so the pool size stops being a limit on throughput for waiting work.
The previews in this release are worth knowing by name so you recognise them in other people's code. Unnamed classes and instance main methods became final in 25. Unnamed patterns and variables became final in 22. Structured concurrency and scoped values continue as previews. String templates (STR."...") were a preview in 21 and 22 and were withdrawn before they ever became final. If you see them in a blog post, do not use them.
Java 22 (March 2024): _ becomes final, native code gets a safe API, and more of a program can run from source
Java 22 is a release of finishing touches. The underscore _ finally means "I do not need this name". The Foreign Function and Memory API, which replaces JNI, becomes final. And the source launcher grows from one file to several.
Three features stay in preview, and two of them get final a release or three later: statements before super(...) (final in 25), stream gatherers (final in 24) and the class-file API (final in 24).
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Unnamed variables and patterns | _ marks a variable or pattern component you do not use: for (var _ : list), catch (Exception _), case Pt(int x, _). | 22 | final |
| Foreign Function and Memory API | Call native libraries and use off-heap memory from Java, safely. It replaces most JNI. | 22 | final |
| Launch multi-file source programs | java Main.java can find and compile other .java files in the same folder. | 22 | final |
Statements before super(...) | Preview; final in 25. | 25 | preview |
| Stream gatherers | Preview; final in 24. | 24 | preview |
| Class-file API | Preview; final in 24. | 24 | preview |
The underscore is the feature you will use most. Every language with pattern matching has one. Before Java 22 a loop that only counted, or a catch that only needed to know the exception happened, still had to invent a variable name, and linters complained about it. Now the code states that the value is not used.
Java 21
Names for variables that are never used.
int count = 0;
for (String x : list) {
count++;
}
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
count = -1;
}Java 22
_ for the loop variable and the exception.
int count = 0;
for (var _ : list) {
count++;
}
try {
Integer.parseInt(s);
} catch (NumberFormatException _) {
count = -1;
}The shift: _ is not a name you can read back. It tells the reader, and the compiler, that nothing uses the value.
import java.util.*;
public class Unnamed22 {
record Pt(int x, int y) {}
public static void main(String[] args) {
int count = 0;
for (var _ : List.of("a", "b", "c")) {
count++;
}
Object o = new Pt(3, 4);
if (o instanceof Pt(int x, _)) {
System.out.println("x = " + x + ", count = " + count);
}
}
}$ javac --release 21 Unnamed22.java
Unnamed22.java:8: error: unnamed variables are not supported in -source 21
for (var _ : List.of("a", "b", "c")) {
^
(use -source 22 or higher to enable unnamed variables)
1 error
[exit 1]
$ javac --release 22 Unnamed22.java
[exit 0]
$ java -cp out Unnamed22
x = 3, count = 3On --release 21 the compiler says "unnamed variables are not supported". On 22 it works. Note that on 21 _ was a reserved word for years and could not be used as a name at all, so code that used it as an identifier had already been broken since Java 9.
Now the launcher. In Java 11 java Hello.java ran one file. If that file used a class from a second file in the same folder, you had to compile properly. Java 22 removes that limit: the launcher looks for the class it needs next to the file you named. The run shows two files, one using the other, on JDK 21 and on JDK 25.
public class Main {
public static void main(String[] args) {
System.out.println(Helper.greet("QuickBite"));
}
}public class Helper {
static String greet(String name) { return "hello, " + name; }
}$ ls
Helper.java
Main.java
$ java Main.java # JDK 21
Main.java:3: error: cannot find symbol
System.out.println(Helper.greet("QuickBite"));
^
symbol: variable Helper
location: class Main
1 error
error: compilation failed
$ java Main.java # JDK 25
hello, QuickBiteJDK 21 fails with cannot find symbol because it compiled only Main.java in memory and never looked for Helper. JDK 25 compiles both. That closes the gap between "script" and "project": a small tool with three files no longer needs a build file.
Java 23 (September 2024): Markdown in doc comments, and previews that finish in 25
Java 23 is the smallest feature release in this stretch. Its visible change is that documentation comments can be written in Markdown instead of HTML.
Two previews arrive here that you will meet again: primitive types in patterns (still preview in 27) and module import declarations (final in 25).
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Markdown documentation comments | Lines starting with /// are Markdown, and the javadoc tool renders them. | 23 | final |
| Primitive types in patterns | Preview; the 5th preview is in Java 27. | not yet | preview |
| Module import declarations | Preview; final in 25. | 25 | preview |
| Generational ZGC is the default ZGC | Choosing ZGC now gives the generational version; the old one goes away. | 23 (JVM) | final |
The old doc comment needed HTML tags for a list, so a short note turned into a block of angle brackets. The Markdown form is what you would type in a pull request. Both compile, because both are just comments; it is the javadoc tool that reads them differently.
Java 22
/** ... */ with HTML tags.
/**
* Returns the total.
* <ul>
* <li>paise, not rupees</li>
* </ul>
* @param lines the line count
*/
static int total(int lines) { return lines; }Java 23
/// lines with Markdown.
/// Returns the total.
///
/// - paise, not rupees
///
/// @param lines the line count
static int total(int lines) { return lines; }The shift: documentation is read as often as it is written, so writing it in the format everybody already knows makes it cheaper to keep up to date.
Java 24 (March 2025): gatherers, and virtual threads that no longer get stuck on synchronized
Java 24 has two changes you will feel. Stream gatherers become final, which means a stream can now do windows, running totals and custom stages. And JEP 491 fixes the biggest complaint about virtual threads: they stopped getting pinned to their carrier thread inside synchronized blocks.
The rest is the JVM getting faster to start, safer for the future, and slightly less crowded with old features.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Stream gatherers | Stream.gather(...) with Gatherers.windowFixed, windowSliding, fold, scan, mapConcurrent and your own. | 24 | final |
Virtual threads and synchronized (JEP 491) | A virtual thread that blocks inside synchronized no longer holds on to its carrier thread. | 24 (JVM) | final |
| Class-file API | A standard way to read and write .class files, replacing internal library use. | 24 | final |
| AOT class loading and linking (JEP 483) | Cache loaded and linked classes from a training run to cut start-up time. | 24 (JVM) | final |
| Post-quantum cryptography | ML-KEM and ML-DSA algorithms in the standard security providers. | 24 | final |
| Security Manager permanently disabled (JEP 486) | The old sandbox can no longer be turned on. | 24 (JVM) | final |
| Compact object headers | Experimental in 24; product feature in 25; default in 27. | 27 | experimental |
Collectors can only run at the end of a pipeline. Gatherers can sit in the middle. A gatherer sees the stream's elements and may emit its own output, keep state, group them in windows, or stop early. Cutting a list into batches of three used to need an index loop. Now it is one stage.
Java 23
An index loop that slices the list.
List<List<Integer>> w = new ArrayList<>();
for (int i = 0; i < nums.size(); i += 3) {
int end = Math.min(i + 3, nums.size());
w.add(nums.subList(i, end));
}Java 24
Gatherers.windowFixed(3) as one stage.
List<List<Integer>> w = nums.stream()
.gather(Gatherers.windowFixed(3))
.toList();The shift: gather is to a stream what a custom collector is to the end of one: a place for stateful logic, but in the middle, so more stages can follow.
import java.util.stream.*;
public class Gather24 {
public static void main(String[] args) {
var days = Stream.of(10, 20, 30, 40, 50)
.gather(Gatherers.windowFixed(2))
.toList();
System.out.println(days);
}
}$ javac --release 23 Gather24.java
Gather24.java:6: error: Gatherers is a preview API and is disabled by default.
.gather(Gatherers.windowFixed(2))
^
(use --enable-preview to enable preview APIs)
Gather24.java:6: error: <R>gather(Gatherer<? super T,?,R>) is a preview API and is disabled by default.
.gather(Gatherers.windowFixed(2))
^
(use --enable-preview to enable preview APIs)
where R,T are type-variables:
R extends Object declared in method <R>gather(Gatherer<? super T,?,R>)
T extends Object declared in interface Stream
2 errors
[exit 1]
$ javac --release 24 Gather24.java
[exit 0]
$ java -cp out Gather24
[[10, 20], [30, 40], [50]]On --release 23 the error is not a missing method but "Gatherers is a preview API and is disabled by default", because in 22 and 23 it was still a preview. Section 06 uses all five built-in gatherers on QuickBite's daily revenue.
The virtual-thread fix needs a longer explanation, because it is the reason many teams waited for Java 24 or 25. Section 12 reproduces it on JDK 21 and JDK 25 and shows what each one prints.
Java 25 (September 2025, LTS): a source file with no class, module imports, and scoped values
Java 25 is the LTS most new projects should choose. It finalises three features that shorten everyday code (compact source files, module imports, flexible constructor bodies) and one that improves concurrency (scoped values).
It is also the JDK that runs every demo on this page.
| Feature | One-liner | Since | Status |
|---|---|---|---|
Compact source files and instance main | A file can start with void main() and no class, and IO.println replaces System.out.println. | 25 | final |
| Module import declarations | import module java.base; imports every public package of a module at once. | 25 | final |
| Flexible constructor bodies | Statements may appear before super(...) or this(...), as long as they do not use this. | 25 | final |
| Scoped values | Share an immutable value down a call chain, bounded to a block, and safe with virtual threads. | 25 | final |
| Key derivation function API | A standard API for deriving keys from other keys and secrets. | 25 | final |
| Compact object headers | Product feature (opt in); smaller objects, smaller heap. | 25 (JVM) | final |
| Generational Shenandoah, AOT ergonomics | Generational mode for Shenandoah is a product feature; AOT cache setup gets easier. | 25 (JVM) | final |
| Previews | Structured concurrency (5th preview), primitive types in patterns (3rd), stable values. | see text | preview |
Start with the file that has no class. A beginner who writes "hello world" no longer meets public, static, String[] args or System.out in the first five minutes. A script-sized program is just a method. This is a real language-teaching change, and it works for working programs too, as the opening of this section showed.
Java 24
The classic file: class, static, String[], System.out.
class Hello {
public static void main(
String[] args) {
System.out.println("hi");
}
}Java 25
A compact source file: a method and IO.println.
void main() {
IO.println("hi");
}The shift: the class, the static, the argument array and the long print call were all ceremony for the common case, and the compiler now supplies them.
void main() {
IO.println("hello from a compact source file");
}$ javac --release 24 Hello25.java
Hello25.java:1: error: implicitly declared classes are not supported in -source 24
void main() {
^
(use -source 25 or higher to enable implicitly declared classes)
1 error
[exit 1]
$ javac --release 25 Hello25.java
[exit 0]
$ java -cp out Hello25
hello from a compact source fileIt also runs straight from source. Here is the same file under the name HelloCompact.java, run directly, and then compiled with --release 24.
$ cat HelloCompact.java
void main() {
IO.println("hello from a compact source file");
}
$ java HelloCompact.java
hello from a compact source file
$ java --release 24 ... (javac --release 24 HelloCompact.java)
HelloCompact.java:1: error: implicitly declared classes are not supported in -source 24
void main() {
^Second, constructor bodies. In Java 24 and earlier, super(...) had to be the first statement. To validate an argument before passing it up, you needed a static helper method called inside the super(...) call. In 25 you can write the check first.
Java 24
A static helper called from inside super(...).
static class Order extends Base {
Order(int qty) {
super(check(qty));
}
static int check(int q) {
if (q <= 0)
throw new IllegalStateException();
return q;
}
}Java 25
The check is written before super(qty).
static class Order extends Base {
Order(int qty) {
if (qty <= 0)
throw new IllegalStateException();
super(qty);
}
}The shift: validation sits above the call that depends on it, in the order a human reads it. The one rule is that code before super(...) must not use this.
public class Ctor25 {
static class Base {
Base(int qty) { System.out.println("Base qty=" + qty); }
}
static class Order extends Base {
Order(int qty) {
if (qty <= 0) throw new IllegalArgumentException("qty");
super(qty);
}
}
public static void main(String[] args) {
new Order(2);
}
}$ javac --release 24 Ctor25.java
Ctor25.java:8: error: flexible constructors is not supported in -source 24
super(qty);
^
(use -source 25 or higher to enable flexible constructors)
1 error
[exit 1]
$ javac --release 25 Ctor25.java
[exit 0]
$ java -cp out Ctor25
Base qty=2Third, module imports. A file that uses lists, maps, streams and executors usually starts with a block of imports. import module java.base; brings in every public package that the module java.base exports, which covers java.util, java.util.stream, java.util.concurrent, java.io, java.nio.file, java.time and the rest of the usual set.
Java 24
Four single-class imports.
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
class A { }Java 25
import module java.base; for the whole module.
import module java.base;
class A { }The shift: one line replaces a list of imports. Use it for scripts and small tools; many teams will keep explicit imports in large applications, where the list documents what a file depends on.
import module java.base;
public class ImportModule25 {
public static void main(String[] args) {
List<String> xs = new ArrayList<>(List.of("b", "a"));
Collections.sort(xs);
System.out.println(xs);
}
}$ javac --release 24 ImportModule25.java
ImportModule25.java:1: error: module imports are not supported in -source 24
import module java.base;
^
(use -source 25 or higher to enable module imports)
1 error
[exit 1]
$ javac --release 25 ImportModule25.java
[exit 0]
$ java -cp out ImportModule25
[a, b]Scoped values, the fourth, are a concurrency feature and are run in section 12 against ThreadLocal. The three previews in this release are the ones to watch: structured concurrency (a fifth preview), primitive types in patterns (a third) and stable values. The next release renames stable values to lazy constants.
Java 26 (17 March 2026): HTTP/3, and a warning that final will soon mean final
Java 26 added no new final language syntax. Its final features are about the platform: a new protocol in the HTTP client, a cheaper garbage collector, and the first warning about something that will break later.
That warning is the one to understand: it is about code that changes final fields with reflection.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| Prepare to make final mean final (JEP 500) | Warns when deep reflection changes a final field. A later release will block it. | 26 (warning) | final |
| HTTP/3 in the HTTP Client (JEP 517) | HttpClient can speak HTTP/3 over QUIC. | 26 | final |
| AOT object caching with any GC (JEP 516) | The start-up cache from JEP 483 works with every collector. | 26 (JVM) | final |
| G1 throughput (JEP 522) | Less synchronisation between application threads and G1, for higher throughput. | 26 (JVM) | final |
| Applet API removed (JEP 504) | The browser applet classes finally go. | 26 (removal) | final |
| Previews | Structured concurrency (6th), lazy constants (2nd), primitive types in patterns (4th), PEM encodings (2nd); Vector API is in its 11th incubator. | see text | preview |
Every Java programmer is told that a final field cannot change. That is almost true. With reflection, setAccessible(true) and Field.set, code could always overwrite a final field of an ordinary object. Frameworks used this to inject values, serialization libraries to rebuild objects. The JVM also assumes a final field never changes, which stops it from optimising some code. JEP 500 starts to make the rule true.
The plan has three steps. Java 26 prints a warning when deep reflection changes a final field. A later release will refuse and throw. Until then there is a command-line switch to allow it. I have no JDK 26 on this machine, so I cannot show you the warning. What I can run is the code on JDK 25, where the mutation still succeeds without any message.
import java.lang.reflect.Field;
public class FinalMutate {
static class Coupon {
private final int percentOff;
Coupon(int percentOff) { this.percentOff = percentOff; }
int percentOff() { return percentOff; }
}
public static void main(String[] args) throws Exception {
Coupon c = new Coupon(10);
Field f = Coupon.class.getDeclaredField("percentOff");
f.setAccessible(true);
f.setInt(c, 90);
System.out.println("final field now holds " + c.percentOff());
}
}$ java -version
openjdk version "25.0.5.1" 2026-11-17
$ java FinalMutate.java
final field now holds 90The field was final int percentOff, set to 10 in the constructor, and the program changed it to 90 and read it back. A coupon that was meant to be 10 percent off is now 90 percent off. This is the kind of bug the warning will help you find.
If a library of yours does this, list it now, so you are not surprised when a future JDK stops it. Check the release notes of 26 for the exact wording of the warning and the name of the switch.
HTTP/3 is simpler to explain. It is the third major version of the protocol and runs over UDP instead of TCP, so a lost packet only stalls one stream, not every request on the connection. The HttpClient from the Java 11 card can use it, so a service that calls other services over HTTP may see lower tail latency without code changes. It needs the server to support it as well.
Java 27 (15 September 2026): safer defaults, no new language syntax
Java 27 is the newest release at the time of writing. Like 26, it adds no new final language syntax. What changes are defaults: the JVM's garbage collector, the size of every object, and the key exchange in TLS.
Defaults matter because they change behaviour for every application that upgrades, with no code changes.
| Feature | One-liner | Since | Status |
|---|---|---|---|
| G1 is the default GC in all environments (JEP 523) | G1 is chosen even on small machines, where the JVM used to fall back to the Serial collector. Check the release notes for the exact conditions. | 27 (JVM) | final |
| Compact object headers by default (JEP 534) | Every object header shrinks from 12 to 8 bytes on a 64-bit JVM, so the same heap holds more objects. | 27 (JVM) | final |
| Post-quantum hybrid key exchange for TLS 1.3 (JEP 527) | TLS combines a classic key exchange with ML-KEM, so recorded traffic stays safe against a future quantum computer. | 27 (JVM) | final |
| JFR in-process data redaction (JEP 536) | Flight Recorder can remove sensitive data from recordings as they are written. | 27 (JVM) | final |
| Previews | Lazy constants (3rd), primitive types in patterns (5th), structured concurrency (7th), PEM encodings (3rd); Vector API in its 12th incubator. | see text | preview |
Two of these defaults are worth a thought before you upgrade. The first is memory. Smaller object headers mean a heap full of small objects (records, boxed integers, list nodes) shrinks, which can save a noticeable share of memory. The second is the garbage collector: if your containers are tiny and you rely on the old "Serial on small machines" choice, test with G1 before the move.
Looking ahead, Java 28 in March 2027 is planned to carry the first Valhalla feature, value objects (JEP 401). Value objects are classes without identity that the JVM can store flat in memory, and they are the long-awaited fix for the cost of Integer and small data objects. Treat that as planned, not promised, until the release notes say otherwise.
Bridge: preview features, one level down
Java is meant to last decades, so a language feature or API that ships as final is nearly impossible to change later. To avoid shipping mistakes, a new feature goes through a trial period. During the trial it is part of the JDK, fully implemented, but switched off by default. That period is called a preview. A library module in the same state is an incubator.
Figure 21.3 shows six features and how long each stayed in the trial. The pattern is regular: two preview rounds, then final in the next release. Structured concurrency is the outlier. It has been in trial since Java 19 (nine releases in all) and is still a preview in Java 27, because each round taught the designers something that changed the API.
How does the switch work? It has three parts. You compile with --enable-preview and a --release that is the same as the JDK's own version. You run with --enable-preview again. And the compiler stamps the class file with a marker: the minor version number is set to 65535. The runtime refuses to start a class file with that marker unless you passed the flag.
Now watch it. The next program uses StructuredTaskScope, a preview API in Java 25. It forks two subtasks, menu (300 ms) and price (250 ms), and waits for both. The first run is the source launcher with no flag. The second adds --enable-preview --source 25.
import java.util.concurrent.StructuredTaskScope;
public class Scope25 {
static String menu() throws InterruptedException { Thread.sleep(300); return "menu"; }
static String price() throws InterruptedException { Thread.sleep(250); return "price"; }
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
try (var scope = StructuredTaskScope.open()) {
var m = scope.fork(Scope25::menu);
var p = scope.fork(Scope25::price);
scope.join();
System.out.println(m.get() + " + " + p.get() + " in "
+ (System.nanoTime() - t0) / 1_000_000 + " ms");
}
}
}$ java Scope25.java
Scope25.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope;
^
(use --enable-preview to enable preview APIs)
Scope25.java:9: error: StructuredTaskScope is a preview API and is disabled by default.
try (var scope = StructuredTaskScope.open()) {
^
(use --enable-preview to enable preview APIs)
2 errors
error: compilation failed
$ java --enable-preview --source 25 Scope25.java
menu + price in 320 msWithout the flag the compiler refuses both mentions of StructuredTaskScope with "is a preview API and is disabled by default". With the flag, both subtasks run at the same time, so the total is about 320 ms (the slower of the two plus a little), not the 550 ms that running them one after the other would take.
Next, the marker. The commands below compile the class with preview on, read the class-file version with javap, and then try to run it with and without the flag. In the commands, out stands for the folder that holds the compiled class.
$ javac --enable-preview --release 25 Scope25.java
Note: Scope25.java uses preview features of Java SE 25.
Note: Recompile with -Xlint:preview for details.
$ javap -v Scope25.class | grep -E "minor|major"
minor version: 65535
major version: 69
$ java -cp . Scope25 # no flag
Error: LinkageError occurred while loading main class Scope25
java.lang.UnsupportedClassVersionError: Preview features are not enabled for Scope25 (class file version 69.65535). Try running with '--enable-preview'
$ java --enable-preview -cp . Scope25
menu + price in 338 msmajor version: 69 is Java 25. minor version: 65535 is the preview marker. Without the flag the JVM refuses to load the class and says so in plain words. With the flag it runs.
Why you cannot ship it: a class file stamped with the preview marker only runs on the exact feature release that built it. A class compiled with preview on Java 25 will not run on Java 26, even with the flag, because the preview may have changed in between. So a preview feature in production code would break at the next JDK upgrade. Use previews in experiments, in tests of ideas, and in tools you rebuild with every JDK, never in a library you publish.
The timeline for structured concurrency is a good lesson in reading release notes. Each row below is another round, and each round is a promise only for that release.
| Release | Status | What to remember |
|---|---|---|
| 19, 20 | Incubator module | A separate module, jdk.incubator.concurrent, which you had to add explicitly. |
| 21 | First preview | Moved into java.base as a preview API; virtual threads are now final. |
| 22 to 24 | Second to fourth preview | Small API adjustments between rounds. |
| 25 | Fifth preview | The way a scope is created changes: StructuredTaskScope.open() instead of constructors. This is the API the demo above uses. |
| 26, 27 | Sixth and seventh preview | Still preview. There is no promised final date, so plan as if it could stay a preview for a while. |
The one-liner cheat sheet
This is the reference table for the whole section. It has 87 rows in ten groups: 81 lines of Java and 6 shell commands. Each row has a task, the shortest correct way to do it in modern Java, and the release that first allowed it.
Every Java row was compiled, not just written down. I generated one source file per release number from the "Since" column and compiled each with javac --release N (14 files, one per distinct Since value, all clean). Then every row from 9 onwards was compiled again alone with --release N-1, and all 66 of them failed. The Java 8 rows cannot be tested one release lower, because JDK 25's javac does not support --release 7. The scripts and results are in code/e21-modern-java/A/cheatsheet/.
A one-liner is the line you would type. In a few rows the example assumes names declared elsewhere: list is a List<String>, map is a Map<String, Integer>, s is a String, o is an Object, p is a Path, opt is an Optional<String>. Some rows are expressions (they produce a value) and some are statements.
Collections & maps
| Task | One-liner | Since |
|---|---|---|
| Immutable list | List.of("a", "b", "c") | 9 |
| Immutable set | Set.of(1, 2, 3) | 9 |
| Immutable map | Map.of("a", 1, "b", 2) | 9 |
| Immutable map, more than 10 pairs | Map.ofEntries(Map.entry("a", 1), Map.entry("b", 2)) | 9 |
| Defensive copy that cannot change later | List.copyOf(list) | 10 |
| Read with a default | map.getOrDefault("k", 0) | 8 |
| Count occurrences | map.merge("k", 1, Integer::sum); | 8 |
| Group into a list per key | mm.computeIfAbsent("k", k -> new ArrayList<>()).add("v"); | 8 |
| Remove by condition | list.removeIf(x -> x.isEmpty()) | 8 |
| Walk a map | map.forEach((k, v) -> System.out.println(k + "=" + v)); | 8 |
| First element | list.getFirst() | 21 |
| Last element | list.getLast() | 21 |
| Reverse view | list.reversed() | 21 |
| Typed array from a collection | list.toArray(String[]::new) | 11 |
| Keep a number inside a range | Math.clamp(150, 0, 100) | 21 |
Strings & text
| Task | One-liner | Since |
|---|---|---|
| Is it empty or only spaces? | s.isBlank() | 11 |
| Trim (Unicode-aware) | s.strip() | 11 |
| Repeat | "=".repeat(20) | 11 |
| Split into lines | s.lines().count() | 11 |
| Join with a separator | String.join(", ", list) | 8 |
| Fill a template | "Order %d: %s".formatted(7, "ok") | 15 |
| Multi-line string | | 15 |
| Indent every line | s.indent(2) | 12 |
| Pipe a string through a function | s.transform(String::strip) | 12 |
| Repeat inside a StringBuilder | new StringBuilder().repeat("ab", 3) | 21 |
| Bytes to hex | HexFormat.of().formatHex(new byte[] {1, 2, (byte) 255}) | 17 |
| Base64 encode | Base64.getEncoder().encodeToString("hi".getBytes()) | 8 |
Files & I/O
| Task | One-liner | Since |
|---|---|---|
| Read a whole file | Files.readString(p) | 11 |
| Write a whole file | Files.writeString(p, "hello") | 11 |
| Stream the lines of a file | Files.lines(p) | 8 |
| Copy one stream into another | new ByteArrayInputStream(new byte[0]).transferTo(System.out) | 9 |
| Find the first differing byte of two files | Files.mismatch(p, p) | 12 |
Optional
| Task | One-liner | Since |
|---|---|---|
| Run one branch or the other | opt.ifPresentOrElse(System.out::println, () -> System.out.println("none")); | 9 |
| Fall back to another Optional | opt.or(() -> Optional.of("fallback")) | 9 |
| Throw if empty (no argument) | opt.orElseThrow() | 10 |
| Is it empty? | opt.isEmpty() | 11 |
| Turn into a 0-or-1 element stream | opt.stream() | 9 |
| Default computed only when needed | opt.orElseGet(() -> "x") | 8 |
Streams & collectors
| Task | One-liner | Since |
|---|---|---|
| Collect to an unmodifiable list | list.stream().filter(x -> !x.isEmpty()).toList() | 16 |
| Take while a condition holds | Stream.of(1, 2, 3, 4).takeWhile(i -> i < 3).count() | 9 |
| Skip while a condition holds | Stream.of(1, 2, 3, 4).dropWhile(i -> i < 3).count() | 9 |
| A for-loop as a stream | Stream.iterate(1, i -> i <= 100, i -> i * 2).count() | 9 |
| Stream of one value or none | Stream.ofNullable(s).count() | 9 |
| Zero, one or many outputs per input | list.stream().<String>mapMulti((x, sink) -> { sink.accept(x); sink.accept(x); }).count() | 16 |
| Two collectors in one pass | list.stream().collect(Collectors.teeing(Collectors.counting(), Collectors.joining(), (c, j) -> c + j)) | 12 |
| Filter inside a group | list.stream().collect(Collectors.groupingBy(String::length, Collectors.filtering(x -> x.startsWith("a"), Collectors.toList()))) | 9 |
| Unmodifiable collector result | list.stream().collect(Collectors.toUnmodifiableList()) | 10 |
| Negate a predicate | list.stream().filter(Predicate.not(String::isBlank)).count() | 11 |
| Sums without boxing | IntStream.rangeClosed(1, 5).sum() | 8 |
| Count, min, max, average at once | IntStream.of(1, 2, 3).summaryStatistics() | 8 |
| Fixed-size batches | Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowFixed(2)).count() | 24 |
| Running total | Stream.of(1, 2, 3).gather(Gatherers.scan(() -> 0, Integer::sum)).count() | 24 |
| Map with a bounded number of virtual threads | Stream.of(1, 2, 3).gather(Gatherers.mapConcurrent(4, i -> i * 2)).count() | 24 |
Records, sealed & patterns
| Task | One-liner | Since |
|---|---|---|
| A data class | record Pt(int x, int y) {} | 16 |
| Validate in a record | | 16 |
| Test and cast in one step | if (o instanceof String t && !t.isEmpty()) System.out.println(t); | 16 |
| A closed set of types | | 17 |
| Take a record apart | if (o instanceof Pt(int x, int y)) System.out.println(x + y); | 21 |
| Ignore a value you do not need | if (o instanceof Pt(int x, _)) System.out.println(x); | 22 |
| Ignore a loop variable | int c = 0; for (var _ : list) c++; | 22 |
switch
| Task | One-liner | Since |
|---|---|---|
| Value from a switch | switch (s.length()) { case 0 -> "empty"; case 1, 2 -> "short"; default -> "long"; } | 14 |
| Block with a result | switch (n) { case 1, 2 -> "small"; default -> { String t = "big"; yield t; } } | 14 |
| Switch on type, with a guard | switch (o) { case Integer i when i > 9 -> "big"; case Integer i -> "int"; case String t -> t; default -> "?"; } | 21 |
| Handle null inside the switch | switch (o) { case null -> "none"; default -> "some"; } | 21 |
Concurrency
| Task | One-liner | Since |
|---|---|---|
| Start a virtual thread | Thread.startVirtualThread(() -> System.out.println("hi")) | 21 |
| Build a named virtual thread | Thread.ofVirtual().name("v-", 0).start(() -> {}) | 21 |
| One virtual thread per task | Executors.newVirtualThreadPerTaskExecutor() | 21 |
| Executor that closes itself | try (var ex = Executors.newFixedThreadPool(4)) { ex.submit(() -> 1); } | 19 |
| Fail a future after a time | CompletableFuture.supplyAsync(() -> 1).orTimeout(2, TimeUnit.SECONDS) | 9 |
| Fall back to a value after a time | CompletableFuture.supplyAsync(() -> 1).completeOnTimeout(0, 2, TimeUnit.SECONDS) | 9 |
| Combine two futures | CompletableFuture.supplyAsync(() -> 1).thenCombine(CompletableFuture.supplyAsync(() -> 2), Integer::sum) | 8 |
| Counter built for many threads | new java.util.concurrent.atomic.LongAdder() | 8 |
| Give platform threads a name | Thread.ofPlatform().name("notify-", 0).factory() | 21 |
| Sleep with a Duration | Thread.sleep(java.time.Duration.ofMillis(1)); | 19 |
| Pass a value down a call chain | ScopedValue.where(ScopedValue.newInstance(), "x").run(() -> {}); | 25 |
HTTP & time
| Task | One-liner | Since |
|---|---|---|
| An HTTP client | HttpClient.newHttpClient() | 11 |
| An HTTP request | HttpRequest.newBuilder(URI.create("https://x.io")).build() | 11 |
| Date plus a day | LocalDate.parse("2026-11-28").plusDays(1) | 8 |
| Time between two moments | Duration.between(Instant.now(), Instant.now()) | 8 |
| Hours part of a duration | Duration.ofMinutes(90).toHoursPart() | 9 |
| Pick a random generator by name | RandomGenerator.of("L64X128MixRandom").nextInt(10) | 17 |
Tooling & launch
These are commands, not Java source, so they were run instead of compiled: jshell, java Hello11.java, jwebserver and the multi-file launch appear with their real output in the cards above.
| Task | Command | Since |
|---|---|---|
| Try a line without a class | jshell | 9 |
| Run a source file with no compile step | java Hello.java | 11 |
| Serve a folder over HTTP | jwebserver -p 8000 | 18 |
| Run a program of several source files | java Main.java (finds Helper.java next to it) | 22 |
| Run a file that has no class | java HelloCompact.java where the file starts with void main() | 25 |
| Try a preview feature | java --enable-preview --source 25 App.java | 25 (per release) |
How to use the table in practice. When you review code that looks old, find the row that matches and propose the one-liner. When you write new code, scan the group for the task you are about to code by hand. When a build breaks after an upgrade, the Since column tells you which release the code needs.
Which version should you target?
This is a stack choice, and the usual rules apply: more than one option, one recommendation, and a reason to switch. The options are the LTS releases and the newest release. A non-LTS release gets patches for only six months, so it suits experiments and tools, not services that must be maintained for years.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Java 8 | You are stuck with an old app server, or a vendor product, and the upgrade is planned for later. | No var, records, switch expressions, text blocks or modern HTTP. Public updates from many vendors have ended or are paid. |
| Java 11 | You are mid-migration from 8 and want a first stop with the standard HttpClient and var. | Missing records, pattern matching and virtual threads. Support is already ending at many vendors. |
| Java 17 | Your frameworks support 17 but not yet 21, and you want records, sealed types, text blocks and switch expressions. | No virtual threads, no sequenced collections, and no final pattern matching in switch. Strong encapsulation will already have forced library upgrades. |
| Java 21 | You want virtual threads and pattern matching and your dependencies are certified for 21. | No scoped values, no compact source files or flexible constructors, and virtual threads can still pin inside synchronized. |
| Java 25 | New projects and teams that can upgrade dependencies: you get everything final in this chapter up to 25, including the synchronized pinning fix from 24. | Dependencies must support 25; generated bytecode and agents may need updates. The next LTS is 29 in September 2027, so plan the following jump. |
| Java 26 or 27 (non-LTS) | A tool or experiment where you want the newest defaults, and you rebuild with every release. | Six months of patches, then you must move again. Preview features are tied to the exact release. |
Three practical tools make a target concrete. In a Maven build, set maven.compiler.release to the target number: that is --release under another name, and it checks both syntax and library calls. In Gradle, this setting:
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}asks Gradle for a JDK of that version and downloads one if needed, so every developer and the CI server compile with the same JDK. And you can run the same project against several JDKs in CI to find the failures early.
# illustrative
Maven pom.xml: <maven.compiler.release>21</maven.compiler.release>
Gradle: java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
CI matrix: run the test suite on JDK 17, 21 and 25A rule of thumb for libraries: compile with --release set to the oldest Java you promise to support, and test on every Java above it. For applications: pick the newest LTS your dependencies allow, and upgrade the JDK in CI before you change any language level. Chapter section 12 and the drill answers come back to this in Q24, the library-release question.
That ends the version tour. From here the chapter builds the two skills that make modern Java worth having: lambdas and streams, then threads and concurrency, starting with the lambda.
04 · Lambdas, functional interfaces and OptionalLambdas, Functional Interfaces, Method References and Optional
A lambda is a short piece of code you can pass around like a value. Java turns it into an object that implements a one-method interface, so every lambda has an interface type. Streams, collectors, Optional and executors all take lambdas, so this section is the foundation for the next three. You will learn the four core interface shapes, the rule about captured variables, the four kinds of method reference, and how to use Optional without hurting yourself.
A QuickBite developer is adding coupons. Each coupon is tied to one restaurant and gives a percentage off. The rule: build one discount function per coupon, then apply every function to an order and add up the discounts.
The developer writes it the way Java 7 code was written, with an anonymous inner class (a class with no name, defined at the place where it is used). Because an anonymous class cannot see a changing loop variable, they copy the current coupon into a field and read the field inside the class.
Order 1 comes from Spice Hut and costs 54,700 paise (Rs 547.00). The Spice Hut coupon is 10%, so the discount should be 5,470 paise. This is what the program prints.
import java.util.*;
import java.util.function.*;
public class CouponBug {
record Coupon(String restaurant, int percentOff) {}
// Java 7 habit: a field that the anonymous class "shares"
static Coupon current;
public static void main(String[] args) {
List<Coupon> coupons = List.of(
new Coupon("Spice Hut", 10),
new Coupon("Dosa Corner", 20),
new Coupon("Pizza Lane", 15));
List<Function<Order, Integer>> discounts = new ArrayList<>();
for (Coupon c : coupons) {
current = c; // copy into the field
discounts.add(new Function<Order, Integer>() {
public Integer apply(Order o) {
return o.restaurant().equals(current.restaurant())
? o.totalCents() * current.percentOff() / 100 : 0;
}
});
}
Order spice = Data.ORDERS.get(0); // Spice Hut, 54,700 paise
System.out.println("order 1 (" + spice.restaurant() + ") total = " + spice.totalCents());
System.out.println("expected discount (10%) = " + spice.totalCents() * 10 / 100);
int got = 0;
for (Function<Order, Integer> f : discounts) got += f.apply(spice);
System.out.println("discount actually applied = " + got);
}
}order 1 (Spice Hut) total = 54700
expected discount (10%) = 5470
discount actually applied = 0The discount is 0. Nobody gets a coupon, and nothing crashed. Here is why. The loop finishes before any discount function runs. By then the field current holds the last coupon (Pizza Lane), so all three functions look at Pizza Lane. The Spice Hut order matches none of them.
A week later another developer rewrites the loop with lambdas and keeps the same idea: one local variable, reassigned on every turn. This time the compiler refuses.
import java.util.*;
import java.util.function.*;
public class CouponLambdaFail {
record Coupon(String restaurant, int percentOff) {}
public static void main(String[] args) {
List<Coupon> coupons = List.of(
new Coupon("Spice Hut", 10), new Coupon("Dosa Corner", 20));
List<Function<Order, Integer>> discounts = new ArrayList<>();
Coupon current = null;
for (Coupon c : coupons) {
current = c;
discounts.add(o -> o.restaurant().equals(current.restaurant())
? o.totalCents() * current.percentOff() / 100 : 0);
}
}
}CouponLambdaFail.java:14: error: local variables referenced from a lambda expression must be final or effectively final
discounts.add(o -> o.restaurant().equals(current.restaurant())
^
CouponLambdaFail.java:15: error: local variables referenced from a lambda expression must be final or effectively final
? o.totalCents() * current.percentOff() / 100 : 0);
^
2 errorsThe compiler caught the very bug that the field trick hid. The message says a local variable used inside a lambda must be final or effectively final, which means: assigned once and never changed. The correct fix is to use the loop's own variable c. A for (Coupon c : coupons) loop makes a new c on every turn, and each new one is assigned once.
import java.util.*;
import java.util.function.*;
public class CouponLambda {
record Coupon(String restaurant, int percentOff) {}
public static void main(String[] args) {
List<Coupon> coupons = List.of(
new Coupon("Spice Hut", 10),
new Coupon("Dosa Corner", 20),
new Coupon("Pizza Lane", 15));
List<Function<Order, Integer>> discounts = new ArrayList<>();
for (Coupon c : coupons) { // c is a fresh variable per turn
discounts.add(o -> o.restaurant().equals(c.restaurant())
? o.totalCents() * c.percentOff() / 100 : 0);
}
Order spice = Data.ORDERS.get(0);
int got = 0;
for (Function<Order, Integer> f : discounts) got += f.apply(spice);
System.out.println("discount applied = " + got);
}
}discount applied = 5470Now each discount function remembers its own coupon. The answer is 5,470, the same as the hand calculation. The rest of this section explains what a lambda is, why that compiler rule exists, and which tools build on lambdas.
The QuickBite sample data used in sections 04 to 07
Every program in sections 04 to 07 uses the same twelve orders, so you can check the numbers by hand. An Order has a restaurant, a customer, a city, a day, a status and a list of order lines. Money is stored in whole paise (priceCents is the field name used across the whole course, so one rupee is 100). The three files below sit in one folder. A program such as CouponLambda.java reads Data.ORDERS from them.
record Line(String item, int qty, int priceCents) {}import java.util.*;
record Order(int id, String restaurant, String customer, String city,
String day, String status, List<Line> lines) {
int totalCents() {
return lines.stream().mapToInt(l -> l.qty() * l.priceCents()).sum();
}
}import java.util.*;
class Data {
static final List<Order> ORDERS = List.of(
new Order(1, "Spice Hut", "asha", "Bengaluru", "2026-11-28", "DELIVERED", List.of(new Line("biryani",2,24900), new Line("raita",1,4900))),
new Order(2, "Dosa Corner", "ravi", "Bengaluru", "2026-11-28", "DELIVERED", List.of(new Line("masala dosa",3,9900))),
new Order(3, "Spice Hut", "meera", "Mysuru", "2026-11-28", "CANCELLED", List.of(new Line("paneer tikka",1,21900))),
new Order(4, "Pizza Lane", "asha", "Bengaluru", "2026-11-29", "DELIVERED", List.of(new Line("margherita",1,34900), new Line("coke",2,6000))),
new Order(5, "Dosa Corner", "kiran", "Mysuru", "2026-11-29", "DELIVERED", List.of(new Line("idli",4,4900), new Line("filter coffee",2,3900))),
new Order(6, "Spice Hut", "ravi", "Bengaluru", "2026-11-29", "DELIVERED", List.of(new Line("biryani",1,24900))),
new Order(7, "Pizza Lane", "meera", "Mysuru", "2026-11-29", "PREPARING", List.of(new Line("farmhouse",2,39900))),
new Order(8, "Dosa Corner", "asha", "Bengaluru", "2026-11-30", "DELIVERED", List.of(new Line("masala dosa",2,9900), new Line("filter coffee",2,3900))),
new Order(9, "Spice Hut", "kiran", "Mysuru", "2026-11-30", "DELIVERED", List.of(new Line("biryani",3,24900), new Line("raita",3,4900))),
new Order(10, "Pizza Lane", "ravi", "Bengaluru", "2026-11-30", "CANCELLED", List.of(new Line("margherita",1,34900))),
new Order(11, "Dosa Corner", "meera", "Mysuru", "2026-11-30", "DELIVERED", List.of(new Line("rava dosa",2,11900))),
new Order(12, "Spice Hut", "asha", "Bengaluru", "2026-11-30", "PREPARING", List.of(new Line("paneer tikka",2,21900), new Line("biryani",1,24900)))
);
}Every demo is started with java Name.java from that folder. Since JDK 22 the launcher compiles the other .java files it needs on the fly, so there is no separate compile step. Totals you can verify: order 1 is 2 × 24,900 + 1 × 4,900 = 54,700 paise, and the twelve orders together are 529,700 paise (Rs 5,297.00).
Functional interfaces: the four core shapes
Java is built on classes, so a lambda cannot be a loose piece of code. It must become an object, and the object needs a type that says how to call it. That type is a functional interface: an interface with exactly one abstract method (a method with no body, which the implementer must supply).
Predicate<T> is one. Its only abstract method is boolean test(T t). When you write s -> s.isEmpty() where a Predicate<String> is expected, the compiler sees one parameter and a boolean result, matches the lambda to test, and builds an object whose test runs your code.
So what does the compiler do with a lambda that has no matching interface? It stops. A lambda cannot go into Object, because Object has no single abstract method to bind to. It also cannot go into List, which has dozens.
public class NotFunctional {
public static void main(String[] args) {
Object o = () -> System.out.println("hi");
Runnable r = () -> System.out.println("hi");
java.util.List<String> l = () -> 1;
}
}NotFunctional.java:3: error: incompatible types: Object is not a functional interface
Object o = () -> System.out.println("hi");
^
NotFunctional.java:5: error: incompatible types: List is not a functional interface
java.util.List<String> l = () -> 1;
^
multiple non-overriding abstract methods found in interface List
2 errorsThe Runnable line compiled without a word. Only the two lines that name a type without a single abstract method were rejected.
You rarely write your own functional interface, because java.util.function already has about 43 of them. They look like many names, but they are variations on four shapes. Think of each shape as a question about what goes in and what comes out.
java.util.function is a variation on these.Read the figure row by row. Function transforms. Predicate answers yes or no, and is what filter wants. Supplier produces a value when asked and takes nothing, which makes it ideal for "compute this later". Consumer takes a value and does something with it, so it returns nothing. BiFunction takes two inputs. UnaryOperator and BinaryOperator are Function and BiFunction where every type is the same, and reduce wants a BinaryOperator.
The last row is the primitive family. IntPredicate takes a plain int instead of an Integer object. Boxing (wrapping an int in an Integer) costs memory and time, and in section 05 you will measure it. This program uses ten of the interfaces once each, so every shape has a real run.
import java.util.*;
import java.util.function.*;
public class Shapes {
public static void main(String[] args) {
Order o = Data.ORDERS.get(0);
Function<Order, String> nameOf = x -> x.restaurant(); // in -> out
Predicate<Order> bigOrder = x -> x.totalCents() > 50000; // in -> boolean
Supplier<String> today = () -> "2026-11-30"; // nothing -> out
Consumer<Order> printer = x -> System.out.println(" consumed order " + x.id()); // in -> nothing
BiFunction<Integer,Integer,Integer> lineTotal = (qty, price) -> qty * price; // two in -> out
UnaryOperator<String> shout = s -> s.toUpperCase(); // T -> T
BinaryOperator<Integer> add = (a, b) -> a + b; // (T, T) -> T
IntPredicate isEven = n -> n % 2 == 0; // int -> boolean, no boxing
ToIntFunction<Order> cents = Order::totalCents; // in -> int
IntBinaryOperator max = Math::max; // (int, int) -> int
System.out.println("Function : " + nameOf.apply(o));
System.out.println("Predicate : " + bigOrder.test(o));
System.out.println("Supplier : " + today.get());
System.out.print ("Consumer :\n"); printer.accept(o);
System.out.println("BiFunction : " + lineTotal.apply(2, 24900));
System.out.println("UnaryOperator : " + shout.apply("spice hut"));
System.out.println("BinaryOperator: " + add.apply(3, 4));
System.out.println("IntPredicate : " + isEven.test(12));
System.out.println("ToIntFunction : " + cents.applyAsInt(o));
System.out.println("IntBinaryOp : " + max.applyAsInt(7, 11));
}
}Function : Spice Hut
Predicate : true
Supplier : 2026-11-30
Consumer :
consumed order 1
BiFunction : 49800
UnaryOperator : SPICE HUT
BinaryOperator: 7
IntPredicate : true
ToIntFunction : 54700
IntBinaryOp : 11The primitive variants follow a naming pattern, so you do not need to memorise them. Put Int, Long or Double in front of the shape (IntFunction, LongPredicate, DoubleUnaryOperator). Or put ToInt in the middle when only the result is primitive (ToIntFunction<T>, ToLongBiFunction<T,U>).
| Interface | Method | Where you meet it |
|---|---|---|
ToIntFunction<T> | int applyAsInt(T) | mapToInt(Order::totalCents), summingInt |
IntFunction<R> | R apply(int) | IntStream.mapToObj(i -> "row " + i) |
IntPredicate | boolean test(int) | IntStream.filter(n -> n % 2 == 0) |
IntUnaryOperator | int applyAsInt(int) | IntStream.map(n -> n * 2) |
IntBinaryOperator | int applyAsInt(int, int) | IntStream.reduce(0, Math::max) |
BooleanSupplier, IntSupplier | getAsBoolean(), getAsInt() | Cheap checks and counters without boxing |
ObjIntConsumer<T> | void accept(T, int) | Custom collectors and accumulators |
Finally, @FunctionalInterface is an optional annotation. It does nothing at run time. Its only job is to make the compiler reject the interface if someone later adds a second abstract method, which would silently break every lambda assigned to it. Put it on any interface you design for lambdas. Interfaces may still have default and static methods, because those are not abstract; Predicate has several (and, or, negate).
Bridge: what a lambda is, one level down
You now know the target type of a lambda. The next question is what the compiler and the JVM actually build. Is a lambda an anonymous class with shorter syntax? Compile one class that has an anonymous class, a lambda and a method reference, then look at the files on disk and the bytecode.
Make the invisible visible: the class files on disk, then the bytecode of each of the three methods.
import java.util.function.Predicate;
public class Outer {
Predicate<String> anon() {
return new Predicate<String>() {
public boolean test(String s) { return s.isEmpty(); }
};
}
Predicate<String> lambda() {
return s -> s.isEmpty();
}
Predicate<String> ref() {
return String::isEmpty;
}
}$ ls out
Outer$1.class
Outer.class
$ javap -c -p -cp out Outer (trimmed)
java.util.function.Predicate<java.lang.String> anon();
0: new #7 // class Outer$1
8: areturn
java.util.function.Predicate<java.lang.String> lambda();
0: invokedynamic #12, 0 // InvokeDynamic #0:test:()Ljava/util/function/Predicate;
5: areturn
java.util.function.Predicate<java.lang.String> ref();
0: invokedynamic #16, 0 // InvokeDynamic #1:test:()Ljava/util/function/Predicate;
5: areturn
private static boolean lambda$lambda$0(java.lang.String);Only the anonymous class produced a second file, Outer$1.class. In the bytecode, anon() runs new Outer$1, an ordinary object creation. The lambda and the method reference both compile to a single instruction named invokedynamic, and no class file exists for them.
The lambda's body did not vanish. The compiler placed it in a private static method called lambda$lambda$0 inside Outer. The invokedynamic instruction is a request to the JVM: "when this line first runs, give me an object that implements Predicate and calls that method." The JVM builds that class in memory at run time, once, and reuses it.
What you see: the runtime class names of an anonymous class and a lambda, printed by the program itself.
import java.util.function.Predicate;
public class LambdaClassName {
public static void main(String[] args) {
Predicate<String> anon = new Predicate<>() {
public boolean test(String s) { return s.isEmpty(); }
};
Predicate<String> lambda = s -> s.isEmpty();
System.out.println("anonymous: " + anon.getClass().getName());
System.out.println("lambda : " + lambda.getClass().getName().replaceAll("0x[0-9a-f]+", "0x..."));
System.out.println("lambda is hidden class: " + lambda.getClass().isHidden());
System.out.println("interfaces: " + java.util.Arrays.toString(lambda.getClass().getInterfaces()));
}
}anonymous: LambdaClassName$1
lambda : LambdaClassName$$Lambda/0x...
lambda is hidden class: true
interfaces: [interface java.util.function.Predicate]The anonymous class has a normal name stored in a file. The lambda's class has a generated name and is a hidden class, which means it cannot be found by name and exists only in memory. This is why the shrinking in Fig. 21.5 costs nothing at run time: fewer lines, fewer files, and the same behaviour.
One more difference is worth a sentence. Inside an anonymous class, this means the anonymous object itself. Inside a lambda, this means the enclosing object, because a lambda is only a piece of the method around it. Mixing these two up is a classic source of confusion when old code is converted.
Java 7 · anonymous class
Eight lines to say "shorter names first, then alphabetical". Most of the text is ceremony.
Collections.sort(names,
new Comparator<String>() {
public int compare(String a,
String b) {
int c = Integer.compare(
a.length(), b.length());
return c != 0 ? c
: a.compareTo(b);
}
});Java 8 · lambda and method refs
The same rule, read left to right as a sentence.
names.sort(
Comparator.comparingInt(String::length)
.thenComparing(
Comparator.naturalOrder()));The shift: you stop writing the container for the code and write the code. Both programs were compiled and run on a real JDK 8, and both print the same line.
openjdk version "1.8.0_514"
[Idli Hub, Spice Hut, Pizza Lane, Dosa Corner]Bridge: why captured variables must be effectively final
Back to the compile error from the incident. A lambda can use variables from the method around it. This is called capturing. The rule is that a captured local variable must be assigned once and never changed. The compiler calls this "effectively final", meaning it would still compile if you wrote final in front.
The reason is where local variables live. A local variable sits on the stack frame of its method, and that frame disappears when the method returns. A lambda may run much later, perhaps on another thread, long after the method has finished. So the lambda does not point at the variable. It takes a copy of the value when the lambda object is created.
If Java allowed the original to change after that, there would be two copies of one variable with different values. Which one would a reader expect to win? Rather than guess, the language forbids the change. This is also why the compiler error in the incident was a gift: the code that "worked" with a field was really sharing one mutable value among three functions.
- Local variable, assigned once: allowed. The lambda keeps a copy.
- The loop variable of a for-each loop: allowed. A new variable exists on every turn, each assigned once.
- A local variable that is reassigned (
i++,current = c): compile error. Use a fresh variable inside the loop body, or a for-each loop. - A field, or a one-element array that you change inside the lambda: compiles, but you have now built shared mutable state. Be careful, especially with threads and parallel streams (section 07).
The same rule applies to anonymous classes since Java 8. Before Java 8 it was stricter: you had to write final yourself. The "copy into a field" hack in the incident is the old workaround for exactly that restriction.
Method references: four kinds
Sometimes a lambda does nothing except call one method. o -> o.totalCents() takes a value and calls a method on it. For that case Java has a shorter form, the method reference, written Order::totalCents. The two double colons mean "the method with this name". It is the same object under the hood, with the same invokedynamic cost you saw in Fig. 21.5.
There are four kinds, and the only difficult one is the third. In the table, "receiver" means the object a method is called on.
| Kind | Written as | Same as the lambda | Who is the receiver? |
|---|---|---|---|
| 1 · Static method | MethodRefs::withGst | x -> MethodRefs.withGst(x) | There is none. The argument goes to the method. |
| 2 · Bound instance method | shop::addFee | x -> shop.addFee(x) | The object shop, fixed when the reference is made. |
| 3 · Unbound instance method | Order::totalCents | o -> o.totalCents() | The first argument. This is the common one in streams. |
| 4 · Constructor | StringBuilder::new | s -> new StringBuilder(s) | A new object is created each call. |
Kind 2 and kind 3 look alike and behave differently. With shop::addFee the receiver is a specific object that already exists. With Order::totalCents the receiver is whichever Order arrives as the argument. The program below makes all four and then changes the bound object to show that kind 2 keeps pointing at the same one.
import java.util.*;
import java.util.function.*;
public class MethodRefs {
static int withGst(int cents) { return cents * 105 / 100; } // a static method
int fee = 3000; // an instance with state
int addFee(int cents) { return cents + fee; }
public static void main(String[] args) {
Order o = Data.ORDERS.get(0);
// 1. static method: Class::staticMethod
Function<Integer, Integer> a = MethodRefs::withGst;
// 2. bound instance method: instance::method (the instance is fixed now)
MethodRefs shop = new MethodRefs();
Function<Integer, Integer> b = shop::addFee;
// 3. unbound instance method: Class::instanceMethod (first argument becomes the receiver)
Function<Order, Integer> c = Order::totalCents;
// 4. constructor: Class::new
Function<String, StringBuilder> d = StringBuilder::new;
System.out.println("1 static : " + a.apply(10000));
shop.fee = 9999; // change after the reference was made: the SAME object is used
System.out.println("2 bound : " + b.apply(10000) + " (shop.fee is now 9999)");
System.out.println("3 unbound : " + c.apply(o));
System.out.println("4 constructor : " + d.apply("hello").reverse());
// The same four written as lambdas
Function<Integer, Integer> a2 = x -> MethodRefs.withGst(x);
Function<Order, Integer> c2 = x -> x.totalCents();
System.out.println("lambda forms : " + a2.apply(10000) + " " + c2.apply(o));
}
}1 static : 10500
2 bound : 19999 (shop.fee is now 9999)
3 unbound : 54700
4 constructor : olleh
lambda forms : 10500 54700The bound call returned 19,999, which is 10,000 + 9,999. The reference was created while the fee was 3,000, but the receiver is the same object, so it saw the later change to shop.fee. What a bound reference fixes at creation is the object, not its fields. If that surprises you, use a lambda, where the reading happens when the lambda runs.
Composing small functions
Functional interfaces carry default methods that glue small pieces into bigger ones. You write each piece once and name it. This is what makes stream pipelines read like a list of steps.
f.andThen(g): runffirst, feed its result tog. Available onFunction,BiFunctionandConsumer.f.compose(g): the reverse. Rungfirst, thenf. Only onFunction.p.and(q),p.or(q),p.negate(): combine predicates with the usual logic. Both sides are short-circuit, like&&and||.Predicate.not(p)(Java 11): the same asnegate(), but written so it works with a method reference:.filter(Predicate.not(String::isBlank)).
import java.util.function.*;
public class Compose {
public static void main(String[] args) {
Function<Integer, Integer> addGst = c -> c * 105 / 100;
Function<Integer, Integer> addFee = c -> c + 3000;
System.out.println("addGst then addFee : " + addGst.andThen(addFee).apply(10000));
System.out.println("addGst after addFee: " + addGst.compose(addFee).apply(10000));
Predicate<String> blank = String::isBlank;
Predicate<String> notBlank = Predicate.not(blank);
Predicate<String> shortWord = s -> s.length() < 6;
System.out.println("not(isBlank)(\"\") : " + notBlank.test(""));
System.out.println("not(isBlank)(\"idli\") : " + notBlank.test("idli"));
System.out.println("and / or / negate : "
+ notBlank.and(shortWord).test("biryani") + " "
+ notBlank.or(shortWord).test("biryani") + " "
+ shortWord.negate().test("biryani"));
Consumer<String> log = s -> System.out.println("log : " + s);
Consumer<String> save = s -> System.out.println("save : " + s);
log.andThen(save).accept("order 7");
}
}addGst then addFee : 13500
addGst after addFee: 13650
not(isBlank)("") : false
not(isBlank)("idli") : true
and / or / negate : false true true
log : order 7
save : order 7Check the arithmetic by hand. Start from 10,000 paise. andThen adds 5% GST first (10,500) and then a fixed fee of 3,000, giving 13,500. compose applies the fee first (13,000) and then the 5% GST, giving 13,650. Order matters, and the two names are a classic interview trap: a.andThen(b) reads left to right, but a.compose(b) runs b first.
Why does Predicate.not exist at all, when negate() already did the job? Because String::isBlank.negate() is not legal Java. A method reference has no type until it is assigned, so you cannot call a method on it. Predicate.not(String::isBlank) gives the reference a type in its argument position.
Optional: a return value that may be absent
The most common Java crash is the NullPointerException: a method returned null and the caller forgot to check. Optional<T> (Java 8) is a small box that holds either one value or nothing. A method that returns Optional<Order> tells the caller, in its type, "there may be no order here". The compiler cannot force you to check, but the type makes it hard to forget.
The key tools are map (change the value inside, if there is one), flatMap (the same, when your step itself returns an Optional), filter (keep the value only if a test passes), and a few ways out of the box: orElse, orElseGet, orElseThrow, ifPresentOrElse. This program calls each of them on a lookup of an order by id.
import java.util.*;
public class OptionalOps {
// a lookup that may find nothing: the honest use of Optional
static Optional<Order> findOrder(int id) {
return Data.ORDERS.stream().filter(o -> o.id() == id).findFirst();
}
public static void main(String[] args) {
System.out.println("map : " + findOrder(4).map(Order::restaurant));
System.out.println("map (absent) : " + findOrder(99).map(Order::restaurant));
System.out.println("filter : " + findOrder(3).filter(o -> o.status().equals("DELIVERED")));
System.out.println("orElse : " + findOrder(99).map(Order::customer).orElse("guest"));
// flatMap: when the step itself returns an Optional
Optional<String> firstItem = findOrder(4)
.flatMap(o -> o.lines().stream().map(Line::item).findFirst());
System.out.println("flatMap : " + firstItem);
// map would nest:
Optional<Optional<String>> nested = findOrder(4)
.map(o -> o.lines().stream().map(Line::item).findFirst());
System.out.println("map (nested) : " + nested);
findOrder(2).ifPresentOrElse(
o -> System.out.println("ifPresentOrElse: found " + o.customer()),
() -> System.out.println("ifPresentOrElse: not found"));
findOrder(99).ifPresentOrElse(
o -> System.out.println("ifPresentOrElse: found " + o.customer()),
() -> System.out.println("ifPresentOrElse: not found"));
System.out.println("or : " + findOrder(99).or(() -> findOrder(1)).map(Order::id));
System.out.println("stream : " + java.util.stream.Stream.of(1, 99, 3, 98)
.map(OptionalOps::findOrder).flatMap(Optional::stream).map(Order::id).toList());
System.out.println("isEmpty : " + findOrder(99).isEmpty());
try {
findOrder(99).orElseThrow();
} catch (NoSuchElementException e) {
System.out.println("orElseThrow(): " + e);
}
try {
findOrder(99).orElseThrow(() -> new IllegalArgumentException("no order 99"));
} catch (IllegalArgumentException e) {
System.out.println("orElseThrow(s): " + e);
}
try {
findOrder(99).get();
} catch (NoSuchElementException e) {
System.out.println("get() : " + e);
}
}
}map : Optional[Pizza Lane]
map (absent) : Optional.empty
filter : Optional.empty
orElse : guest
flatMap : Optional[margherita]
map (nested) : Optional[Optional[margherita]]
ifPresentOrElse: found ravi
ifPresentOrElse: not found
or : Optional[1]
stream : [1, 3]
isEmpty : true
orElseThrow(): java.util.NoSuchElementException: No value present
orElseThrow(s): java.lang.IllegalArgumentException: no order 99
get() : java.util.NoSuchElementException: No value presentLook at the two lines about flatMap and map (nested). The step "first item of an order" itself returns an Optional, so map produces Optional[Optional[margherita]], a box inside a box. flatMap removes one layer. The same name does the same job on streams, as you will see in section 05.
Three small notes. get() exists but throws NoSuchElementException when empty, exactly like the no-argument orElseThrow() that Java 10 added. The newer name states the intent, so prefer it. or() (Java 9) supplies another Optional as a fallback. stream() (Java 9) turns an Optional into a stream of zero or one element, which lets you drop the empty ones inside a pipeline with flatMap(Optional::stream).
| Method | What it does | Since |
|---|---|---|
of, ofNullable, empty | Make a box. of(null) throws, ofNullable(null) gives empty. | 8 |
map, flatMap, filter | Transform or test the value if it is there. | 8 |
orElse, orElseGet | Value or fallback. orElseGet takes a Supplier (lazy). | 8 |
ifPresent | Run a Consumer if present. | 8 |
ifPresentOrElse, or, stream | Both branches in one call, an alternative box, and zero-or-one stream. | 9 |
orElseThrow() | Value or NoSuchElementException. The clear replacement for get(). | 10 |
isEmpty() | The opposite of isPresent(), so you can skip the !. | 11 |
Idiom: orElseGet for work, orElse for constants
The problem: orElse(loadFromDatabase()) looks like "use the database only if the box is empty". It is not. Java evaluates every argument before calling a method, and loadFromDatabase() is an argument, so the query runs on every call, even when the value is present.
How it works: orElse(T other) takes a value. orElseGet(Supplier<T> s) takes a recipe for a value and runs the recipe only when the box is empty. The lambda () -> loadFromDatabase() is just an object until someone calls get() on it.
- Constant or already-computed value:
orElse("guest")is fine. Nothing expensive is hidden. - Method call, query, object creation: use
orElseGet(() -> ...). - A failure instead of a fallback:
orElseThrow(() -> new SomeException(...))is also lazy, the exception object is built only if needed.
Make the invisible visible: the box holds a value, and the "database" costs 200 ms and counts its calls.
import java.util.*;
public class OrElseDemo {
static int dbCalls = 0;
static String loadCouponFromDatabase() {
dbCalls++;
try { Thread.sleep(200); } catch (InterruptedException e) { } // pretend: a 200 ms query
return "WELCOME50";
}
public static void main(String[] args) {
Optional<String> cached = Optional.of("DINNER20"); // the value IS present
long t0 = System.nanoTime();
String a = cached.orElse(loadCouponFromDatabase());
long ms1 = (System.nanoTime() - t0) / 1_000_000;
System.out.println("orElse -> " + a + " db calls = " + dbCalls + " took ~" + ms1 + " ms");
dbCalls = 0;
t0 = System.nanoTime();
String b = cached.orElseGet(() -> loadCouponFromDatabase());
long ms2 = (System.nanoTime() - t0) / 1_000_000;
System.out.println("orElseGet -> " + b + " db calls = " + dbCalls + " took ~" + ms2 + " ms");
dbCalls = 0;
String c = Optional.<String>empty().orElseGet(OrElseDemo::loadCouponFromDatabase);
System.out.println("empty + orElseGet -> " + c + " db calls = " + dbCalls);
}
}orElse -> DINNER20 db calls = 1 took ~200 ms
orElseGet -> DINNER20 db calls = 0 took ~0 ms
empty + orElseGet -> WELCOME50 db calls = 1With orElse, the query ran once and took 200 ms although the answer was never used. With orElseGet, it ran zero times. Only when the box was empty did the lazy version call it. At 500 requests a second, the careless version is 100 wasted seconds of database time every second.
- Works:
orElseGetfor any fallback that costs something (a query, an HTTP call,newof a heavy object, logging with side effects). - Fails:
orElse(expensive())(always runs). AlsoorElse(null): you turned the box back into a null. - Interview takeaway: "
orElseevaluates its argument eagerly, because that is how Java passes arguments.orElseGettakes aSupplier, so the fallback runs only when the Optional is empty."
Idiom: Optional is for return values only
The problem: after learning Optional, developers use it everywhere: as a method parameter, a class field, a list element, or the return type of a method that returns a collection. The code gets longer and the null problem is still there.
How it works: Optional was designed for one job: a method result that is "maybe nothing", where null would be easy to misuse. The designers said so in the documentation. It is an ordinary object, so a variable of type Optional can itself be null. It also does not implement Serializable and adds an extra object per use.
- Return type: yes, for a lookup that can legitimately find nothing (
findOrder(id)). - Parameter: no. Use two overloads, or pass the plain value and let the method handle
nullby contract. - Field: no. Keep the field nullable and give the getter an
Optionalreturn type, if you want one. - Collection or array result: no. An empty list already means "nothing".
import java.util.*;
public class OptionalMisuse {
// Smell 1: an Optional parameter - the caller can still pass null, or Optional.empty()
static String describe(Optional<String> note) {
return note.map(n -> "note: " + n).orElse("no note");
}
// Smell 2: Optional of a collection - there are now THREE kinds of "nothing"
static Optional<List<String>> itemsOf(Order o) {
return o.lines().isEmpty() ? Optional.empty() : Optional.of(o.lines().stream().map(Line::item).toList());
}
// Better: an empty list says "nothing" by itself
static List<String> itemsOfBetter(Order o) {
return o.lines().stream().map(Line::item).toList();
}
public static void main(String[] args) {
System.out.println(describe(Optional.of("no onions")));
System.out.println(describe(Optional.empty()));
try {
System.out.println(describe(null)); // compiles fine
} catch (NullPointerException e) {
System.out.println("describe(null) -> NullPointerException");
}
Order none = new Order(99, "Spice Hut", "x", "Mysuru", "2026-12-01", "PREPARING", List.of());
System.out.println("Optional<List> : " + itemsOf(none) + " vs plain list: " + itemsOfBetter(none));
System.out.println("caller of the Optional version must write: itemsOf(o).orElse(List.of())");
}
}note: no onions
no note
describe(null) -> NullPointerException
Optional<List> : Optional.empty vs plain list: []
caller of the Optional version must write: itemsOf(o).orElse(List.of())The first call shows the promise: Optional as a parameter reads nicely. The third call breaks it, because the caller passed null and got a NullPointerException. The compiler accepted it, so the type gave no protection at all. The last two lines compare the shapes for a collection. Optional<List<String>> has three states (absent, empty list, non-empty list), while List<String> has two.
- Works:
Optional<Order> findOrder(int id),stream.findFirst(),stream.max(...). All of these are return values. - Fails:
void ship(Optional<Address> a),private Optional<String> note;,List<Optional<Order>>,Optional<List<Order>>, and callingget()without checking. - Interview takeaway: "
Optionalis a return type for 'might be absent'. I do not use it for parameters, fields or collections, because it can still be null there and it adds noise without protection."
Idiom: the method reference when a lambda only forwards
The problem: pipelines full of o -> o.customer(), s -> s.trim() and x -> foo(x) are noisy. The reader has to read a parameter name, an arrow and the same name again, just to learn "call customer".
How it works: if a lambda only passes its parameters, in order, straight to one method, replace it with a reference to that method. Order::customer says the same thing in one token that is also a good name. This is the single most common refactoring in stream code.
- Check the shape: the lambda's parameters go to the method in the same order, with nothing added.
- Choose the kind:
Class::instanceMethodforx -> x.m(),Class::staticMethodforx -> Class.m(x),Class::newfor a constructor. - Keep the lambda when you add anything (
o -> o.totalCents() / 100) or when the reference is ambiguous.
The trap: some references have two methods with the same name that both fit. Integer::toString could be the static Integer.toString(int) or the instance toString(). The compiler refuses to pick.
import java.util.stream.*;
public class MethodRefAmbiguous {
public static void main(String[] args) {
System.out.println(Stream.of(1, 2, 3).map(Integer::toString).toList());
}
}MethodRefAmbiguous.java:5: error: incompatible types: cannot infer type-variable(s) R
System.out.println(Stream.of(1, 2, 3).map(Integer::toString).toList());
^
(argument mismatch; invalid method reference
reference to toString is ambiguous
both method toString(int) in Integer and method toString() in Integer match)
where R,T are type-variables:
R extends Object declared in method <R>map(Function<? super T,? extends R>)
T extends Object declared in interface Stream
1 errorThe fix is to pick a form that has only one meaning: String::valueOf, or the lambda i -> Integer.toString(i). This is the one case where the "less typing" form costs you a compile error, and it is not a bug in your logic.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Method reference | The lambda only forwards to one method. Names read well: Order::customer. | Ambiguity errors with overloads (Integer::toString). Harder to put a breakpoint inside. |
| Lambda | The default. One to three lines, you add logic, or you combine fields. | A long multi-line lambda hides a concept that deserves a name. |
| Named method, called by reference | The logic is more than three lines, is reused, or needs a unit test. | One extra method. Almost always worth it. |
| Anonymous class | You need state of its own, several methods, or an interface that is not functional. | Verbose, a separate class file, and this means the anonymous object. |
Switch away from a lambda the moment you catch yourself writing braces and a second variable inside it. Give that logic a name, and pass the name.
- Works:
.map(Order::customer),.mapToInt(Order::totalCents),.forEach(System.out::println),.toArray(String[]::new),.collect(toCollection(TreeSet::new)). - Fails: overloaded names such as
Integer::toString, and anything where the reference hides an argument you actually wanted to add. - Interview takeaway: "If a lambda just forwards its arguments to one method, I use a method reference. There are four kinds: static, bound instance, unbound instance and constructor. The unbound one,
Order::customer, takes the receiver from the first argument."
Lambdas are the grammar of everything that follows. Section 05 uses them to describe each step of a pipeline, and section 10 hands them to thread pools as tasks. In Chapter E3, the same lambdas show up wherever a Callable is submitted.
05 · How a stream pipeline really runsStreams: How a Pipeline Really Runs
A stream is a recipe for processing a sequence of values, not a collection that holds them. You list the steps first (filter, map, sort), and nothing runs until a final "terminal" step pulls the data through. Each element then travels the whole pipeline on its own, one at a time. Knowing that order explains why streams are lazy, why they can be infinite, why you cannot reuse one, and why side effects inside them go wrong.
Two QuickBite developers hit two different stream surprises in the same week. The first wanted a reusable view of delivered orders. They built the stream once, stored it in a static field, and called it from two places. The first call worked. The second crashed.
The second developer wanted to log each order that passes through a pipeline. They added .peek(o -> System.out.println(...)) and saw nothing in the console, so they assumed the code never ran. Both programs below are real runs on the twelve sample orders.
import java.util.*;
import java.util.stream.*;
public class StreamReuse {
// Bug 1: a Stream stored in a field "to reuse"
static final Stream<Order> DELIVERED =
Data.ORDERS.stream().filter(o -> o.status().equals("DELIVERED"));
public static void main(String[] args) {
System.out.println("first use : " + DELIVERED.count() + " delivered orders");
try {
System.out.println("second use: " + DELIVERED.count());
} catch (IllegalStateException e) {
System.out.println("second use: " + e);
}
// Fix: keep a Supplier (or the List), build a fresh stream each time
java.util.function.Supplier<Stream<Order>> delivered =
() -> Data.ORDERS.stream().filter(o -> o.status().equals("DELIVERED"));
System.out.println("supplier : " + delivered.get().count() + " and " + delivered.get().count());
// Bug 2: peek "for logging" with no terminal operation
System.out.println("--- peek without a terminal operation:");
Data.ORDERS.stream().peek(o -> System.out.println("saw order " + o.id()));
System.out.println("(nothing printed above this line)");
System.out.println("--- peek with a terminal operation (toList):");
List<Order> three = Data.ORDERS.stream().limit(3)
.peek(o -> System.out.println("saw order " + o.id())).toList();
System.out.println("got " + three.size() + " orders");
System.out.println("--- peek followed by count():");
long n = Data.ORDERS.stream().limit(3)
.peek(o -> System.out.println("saw order " + o.id())).count();
System.out.println("count = " + n + " (the size was known, so count() skipped the pipeline)");
}
}first use : 8 delivered orders
second use: java.lang.IllegalStateException: stream has already been operated upon or closed
supplier : 8 and 8
--- peek without a terminal operation:
(nothing printed above this line)
--- peek with a terminal operation (toList):
saw order 1
saw order 2
saw order 3
got 3 orders
--- peek followed by count():
count = 3 (the size was known, so count() skipped the pipeline)Read the output from the top. The first count() gives 8 delivered orders. The second count() on the same stream throws this:
IllegalStateException: stream has already been operated upon or closedA stream is a one-shot pipe: once a terminal operation has used it, it is finished.
The fix is to store the recipe, not the pipe. A Supplier<Stream<Order>> builds a fresh stream on each call (the supplier line shows 8 and 8). Often the simplest fix is to keep the List and call .stream() each time, because creating a stream is cheap.
The peek mystery has a different cause. The first block built a pipeline with peek and no terminal operation. Nothing printed, because nothing ran. The second block added toList(), and the three "saw order" lines appeared. The last block hides one more surprise that you will explain after the next bridge: with count(), the lines vanished again, even though count() is a terminal operation.
Bridge: the three parts of a pipeline
Every stream pipeline has exactly three parts, in this order. Fig. 21.6 shows them for a small example.
- A source: where the elements come from.
list.stream(),Stream.of(...),IntStream.range(0, 10),Files.lines(path),Stream.iterate(...). The source holds or generates values. The stream itself does not hold them. - Zero or more intermediate operations:
filter,map,sorted,distinct,limit,flatMap,peek. Each one returns a newStream. Calling one does not process anything. It only adds a step to the recipe. - Exactly one terminal operation:
toList,collect,count,sum,forEach,findFirst,anyMatch,reduce. It does not return a stream. It starts the work and produces the answer.
The second row of the figure is the part that surprises people. The source does not push values forward. The terminal operation pulls: it asks the stage before it for one element, which asks the stage before that, all the way back to the source. That one design choice explains laziness, short-circuiting and the strange element order, which you will now see in turn.
Bridge: laziness, proved by a print statement
"Lazy" means a step does no work until its result is needed. To prove it, put a print statement inside a map and run the pipeline with no terminal operation, then with one. The terminal operation here is findFirst on customer "kiran", who placed order 5.
import java.util.*;
import java.util.stream.*;
public class Lazy {
public static void main(String[] args) {
System.out.println("--- map with a print and no terminal operation:");
Stream<String> s = Data.ORDERS.stream()
.map(o -> { System.out.println(" map order " + o.id()); return o.customer(); });
System.out.println("pipeline built, nothing has run");
System.out.println("--- same pipeline, plus a terminal operation (findFirst on 'kiran'):");
Optional<String> first = Data.ORDERS.stream()
.map(o -> { System.out.println(" map order " + o.id()); return o.customer(); })
.filter(c -> c.equals("kiran"))
.findFirst();
System.out.println("result = " + first);
}
}--- map with a print and no terminal operation:
pipeline built, nothing has run
--- same pipeline, plus a terminal operation (findFirst on 'kiran'):
map order 1
map order 2
map order 3
map order 4
map order 5
result = Optional[kiran]Two facts come out of that. First, building the pipeline printed nothing. Second, the pipeline with findFirst mapped orders 1 to 5 and then stopped. Order 5 was the first match, so orders 6 to 12 were never touched. A loop that mapped everything first and filtered afterwards would have done 12 maps. The stream did 5.
This is also the answer to the peek surprise earlier: peek is an intermediate step, so it runs only when a terminal operation pulls elements through it. And when does the pull skip a step altogether? Since Java 9, count() is allowed to skip the pipeline if it can work out the size without looking at elements. Our source was a list with a limit(3), so the size was known to be 3, and peek never ran.
That is an optimisation the documentation allows, and one more reason not to put real work inside peek. Use it for debugging only.
Bridge: one element at a time, not one stage at a time
Most people imagine a pipeline as assembly stages: filter all the orders first, then map all the survivors. That picture is wrong. Run a trace with prints in both stages to see what really happens.
import java.util.*;
import java.util.stream.*;
public class Vertical {
public static void main(String[] args) {
List<String> r = Data.ORDERS.stream().limit(4)
.filter(o -> { System.out.println("filter " + o.id()); return o.status().equals("DELIVERED"); })
.map(o -> { System.out.println(" map " + o.id()); return o.restaurant(); })
.toList();
System.out.println(r);
System.out.println("--- with sorted() in the middle:");
List<String> r2 = Data.ORDERS.stream().limit(4)
.filter(o -> { System.out.println("filter " + o.id()); return o.status().equals("DELIVERED"); })
.sorted(Comparator.comparing(Order::restaurant))
.map(o -> { System.out.println(" map " + o.id()); return o.restaurant(); })
.toList();
System.out.println(r2);
}
}filter 1
map 1
filter 2
map 2
filter 3
filter 4
map 4
[Spice Hut, Dosa Corner, Pizza Lane]
--- with sorted() in the middle:
filter 1
filter 2
filter 3
filter 4
map 2
map 4
map 1
[Dosa Corner, Pizza Lane, Spice Hut]In the first run, the order is: filter 1, map 1, filter 2, map 2, filter 3, filter 4, map 4. Element 1 went all the way through both stages before element 2 started. Order 3 is CANCELLED, so it stopped at the filter and never reached map. Fig. 21.7 draws the wrong picture beside the real one, using the step numbers from this trace.
Why does the JDK work this way? Memory and speed. A "stage by stage" pipeline would need a full temporary list between every two steps. With 5 million orders, that is millions of throwaway objects. One element at a time needs no intermediate list at all, and it allows early exit. This design is often called loop fusion: the library runs all the stages inside one loop.
The second half of the trace shows the exception to the rule. When sorted() sits between the stages, all four filters ran first, then all three maps. The next bridge explains why.
Bridge: short-circuiting and infinite streams
Because the terminal operation pulls, it can also stop pulling. An operation that can finish without reading every element is called short-circuiting (it takes a shortcut, like && does when the left side is false). The short-circuit operations are findFirst, findAny, anyMatch, allMatch, noneMatch, limit and takeWhile.
This is what makes an infinite stream usable. Stream.iterate(1, i -> i + 1) describes 1, 2, 3, and so on forever. It cannot be put into a list, but it can feed a pipeline that stops early. The program also counts how many orders were really looked at.
import java.util.*;
import java.util.stream.*;
public class ShortCircuit {
static int calls = 0;
public static void main(String[] args) {
// an INFINITE stream: 1, 2, 3, ...
System.out.println("limit : " + Stream.iterate(1, i -> i + 1).limit(5).toList());
System.out.println("findFirst : " + Stream.iterate(1, i -> i + 1).filter(i -> i % 7 == 0).findFirst());
System.out.println("anyMatch : " + Stream.iterate(1, i -> i + 1).anyMatch(i -> i * i > 1000));
System.out.println("takeWhile : " + Stream.iterate(1, i -> i + 1).takeWhile(i -> i < 6).toList());
// how much work is done?
boolean found = Data.ORDERS.stream()
.peek(o -> calls++)
.anyMatch(o -> o.status().equals("CANCELLED"));
System.out.println("anyMatch(CANCELLED) found=" + found + " after looking at " + calls + " of 12 orders");
calls = 0;
long cancelled = Data.ORDERS.stream()
.peek(o -> calls++)
.filter(o -> o.status().equals("CANCELLED"))
.count();
System.out.println("count of CANCELLED = " + cancelled + " after looking at " + calls + " of 12 orders");
// the trap: an operation that is NOT short-circuit never ends
// Stream.iterate(1, i -> i + 1).sorted().findFirst(); // runs out of memory
System.out.println("(sorted() on an infinite stream would never return: it must see everything first)");
}
}limit : [1, 2, 3, 4, 5]
findFirst : Optional[7]
anyMatch : true
takeWhile : [1, 2, 3, 4, 5]
anyMatch(CANCELLED) found=true after looking at 3 of 12 orders
count of CANCELLED = 2 after looking at 12 of 12 orders
(sorted() on an infinite stream would never return: it must see everything first)Compare the last two measured lines. anyMatch found the first CANCELLED order (order 3) after looking at 3 of 12. The filter(...).count() version had to look at all 12, because counting needs every element. Both are correct, and they differ by 9 orders. On a stream of 5 million orders that gap is the difference between instant and several seconds.
The commented line is a warning. sorted() is not short-circuiting. It must read all elements before it can hand over even the first one, so calling it on an infinite stream never returns. The same goes for count, reduce and collect on an infinite stream.
Idiom: ask a short-circuit question, not a counting one
The problem: to answer "is there any cancelled order?" the code counts them all: filter(...).count() > 0. It reads every element, even though the answer is known after the first match.
How it works: the terminal operations anyMatch, allMatch, noneMatch, findFirst and findAny stop pulling as soon as the answer is certain. limit(n) and takeWhile do the same for intermediate steps.
- "Is there one?":
anyMatch(test). - "Are they all fine?":
allMatch(test). It stops at the first failure. - "Give me one":
findFirst(), which returns anOptional. - "Give me the first N":
limit(N), which also lets an infinite source end.
- Works: the numbers above.
anyMatchread 3 elements,countread 12.Stream.iterate(...).limit(5)and.filter(...).findFirst()finish on an infinite source. - Fails:
sorted(),reduceorcollecton an infinite stream. A short-circuit step after them is too late, because they never finish. AlsoallMatchon an empty stream istrue, which surprises people. - Interview takeaway: "If I only need a yes, a no or the first match, I use
anyMatch,allMatchorfindFirst. They stop early, and they are the only way to use an infinite stream.sortedandcounthave to read everything."
Bridge: stateless and stateful operations
The trace in Fig. 21.7 broke its own rule when sorted() appeared. The reason is a split in the intermediate operations. A stateless operation (filter, map, peek, flatMap) looks at each element on its own and remembers nothing, so it can pass an element on at once. A stateful operation (sorted, distinct, limit when the stream is ordered and parallel) has to remember elements it has already seen.
There are two levels of statefulness, and the trace below shows both. distinct() remembers a set of values seen so far, so it can still pass each new value forward immediately. sorted() can never emit anything until it has read the last element, because the last element might be the smallest.
import java.util.*;
import java.util.stream.*;
public class Stateful {
public static void main(String[] args) {
System.out.println("--- distinct() (stateful, but it can pass elements on as it goes):");
Data.ORDERS.stream().limit(6)
.map(o -> { System.out.println(" in " + o.customer()); return o.customer(); })
.distinct()
.forEach(c -> System.out.println(" out " + c));
System.out.println("--- sorted() (stateful, must hold ALL elements before the first one leaves):");
Data.ORDERS.stream().limit(4)
.map(o -> { System.out.println(" in " + o.id()); return o; })
.sorted(Comparator.comparingInt(Order::totalCents))
.forEach(o -> System.out.println(" out " + o.id() + " (" + o.totalCents() + ")"));
System.out.println("--- sorted().limit(2): still reads all 12 to find the cheapest 2");
int[] seen = {0};
List<Integer> cheapest = Data.ORDERS.stream().peek(o -> seen[0]++)
.sorted(Comparator.comparingInt(Order::totalCents)).limit(2).map(Order::id).toList();
System.out.println("cheapest two ids " + cheapest + " after reading " + seen[0] + " orders");
}
}--- distinct() (stateful, but it can pass elements on as it goes):
in asha
out asha
in ravi
out ravi
in meera
out meera
in asha
in kiran
out kiran
in ravi
--- sorted() (stateful, must hold ALL elements before the first one leaves):
in 1
in 2
in 3
in 4
out 3 (21900)
out 2 (29700)
out 4 (46900)
out 1 (54700)
--- sorted().limit(2): still reads all 12 to find the cheapest 2
cheapest two ids [3, 11] after reading 12 ordersWith distinct(), "asha" came out right after it went in, and the repeated "asha" and "ravi" (the second in asha and in ravi) produced no out. With sorted(), all four in lines appear before the first out. The last test shows the cost: even sorted().limit(2) reads all 12 orders to find the cheapest two (orders 3 and 11).
Why does this matter for you? A stateful step is a barrier. Memory use grows with the data size, because it holds everything. In a parallel stream, a barrier is also where the threads must wait for each other. When you can, put filter and limit before sorted to make the pile smaller, and avoid sorting a huge stream just to take a few items. For "top 3 of millions", a small priority queue of three items needs far less memory than sorting everything.
Bridge: map, flatMap and mapMulti
Three operations change the shape of a stream, and they differ in how many outputs one input can produce.
map: exactly one output per input. An order becomes its customer name.flatMap: zero, one or many outputs per input, delivered as a small stream that is then flattened into the main stream. An order becomes its lines.mapMulti(Java 16): the same asflatMap, but you push outputs into a "sink" withsink.accept(x)instead of building a stream. It avoids creating a tiny stream per element, which helps when most inputs produce zero or one output.
The program turns orders into order lines. map gives a stream of lists, which is rarely what you want. flatMap gives one flat stream of lines.
import java.util.*;
import java.util.stream.*;
public class FlatMapDemo {
public static void main(String[] args) {
// map: one order -> one List<Line> (a stream of lists)
System.out.println("map : " + Data.ORDERS.stream().limit(3).map(Order::lines).toList());
// flatMap: one order -> many lines, flattened into ONE stream
System.out.println("flatMap : " + Data.ORDERS.stream().limit(3)
.flatMap(o -> o.lines().stream()).map(Line::item).toList());
// distinct items sold, sorted
System.out.println("items : " + Data.ORDERS.stream()
.flatMap(o -> o.lines().stream()).map(Line::item).distinct().sorted().toList());
// mapMulti (16): same result, no intermediate Stream per order
List<String> viaMulti = Data.ORDERS.stream().limit(3)
.<String>mapMulti((o, sink) -> { for (Line l : o.lines()) sink.accept(l.item()); })
.toList();
System.out.println("mapMulti: " + viaMulti);
// flatMap can also DROP elements: 0 outputs
System.out.println("0 or 1 : " + Data.ORDERS.stream().limit(4)
.flatMap(o -> o.status().equals("DELIVERED") ? Stream.of(o.id()) : Stream.empty()).toList());
}
}map : [[Line[item=biryani, qty=2, priceCents=24900], Line[item=raita, qty=1, priceCents=4900]], [Line[item=masala dosa, qty=3, priceCents=9900]], [Line[item=paneer tikka, qty=1, priceCents=21900]]]
flatMap : [biryani, raita, masala dosa, paneer tikka]
items : [biryani, coke, farmhouse, filter coffee, idli, margherita, masala dosa, paneer tikka, raita, rava dosa]
mapMulti: [biryani, raita, masala dosa, paneer tikka]
0 or 1 : [1, 2, 4]The first line is the problem in one picture: a list of lists of Line records, one inner list per order. The second line is the answer you wanted, four item names from three orders. The third line shows a typical use, "which distinct items were ever sold", which needs the flattening. The fifth line shows that flatMap can also drop elements, by returning an empty stream: orders 1, 2 and 4 are DELIVERED and order 3 vanished.
flatMap is the same idea as the flatMap on Optional that you met in section 04: "my step returns a container, and I want one layer, not two". A small rule of thumb: if your lambda returns a Stream or an Optional and you used map, you probably wanted flatMap.
Bridge: reduce versus collect
reduce combines elements into one value of the same kind: a sum, a maximum, a product. You give it a starting value (the identity) and a function that merges two values. It works because the function creates a new value each time and mutates nothing.
collect builds a mutable container: a list, a map, a string builder. It takes a supplier (make an empty container), an accumulator (put one element in) and a combiner (merge two containers). In a parallel stream, each thread fills its own container, and the combiner joins them.
The trouble starts when someone uses reduce to build a list. The identity new ArrayList<>() is one object, so every thread adds to the same list. This program runs that mistake on 100,000 elements, three times, in a parallel stream.
import java.util.*;
import java.util.stream.*;
public class ReduceVsCollect {
public static void main(String[] args) {
// reduce is right for combining values into ONE value of the same kind
int total = Data.ORDERS.stream().map(Order::totalCents).reduce(0, Integer::sum);
System.out.println("reduce sum of all totals : " + total);
System.out.println("max total via reduce : " + Data.ORDERS.stream().map(Order::totalCents).reduce(Integer::max).get());
// reduce is the WRONG tool for building a mutable container
List<Integer> ids = IntStream.rangeClosed(1, 100_000).boxed().toList();
for (int run = 1; run <= 3; run++) {
try {
ArrayList<Integer> wrong = ids.parallelStream().reduce(
new ArrayList<>(), // ONE shared identity object
(list, x) -> { list.add(x); return list; },
(a, b) -> { a.addAll(b); return a; });
System.out.println("run " + run + " reduce into ArrayList: size = " + wrong.size() + " (expected 100000)");
} catch (Exception e) {
System.out.println("run " + run + " reduce into ArrayList: " + e.getClass().getSimpleName());
}
}
// collect gives every thread its OWN container, then merges them
List<Integer> right = ids.parallelStream().collect(Collectors.toList());
System.out.println("collect into list : size = " + right.size());
}
}reduce sum of all totals : 529700
max total via reduce : 89400
run 1 reduce into ArrayList: ArrayIndexOutOfBoundsException
run 2 reduce into ArrayList: ArrayIndexOutOfBoundsException
run 3 reduce into ArrayList: ArrayIndexOutOfBoundsException
collect into list : size = 100000The two reduce lines at the top are the right use. The three parallel runs that follow were all broken: all three crashed with ArrayIndexOutOfBoundsException, because several threads grew the same ArrayList at once. In the sequential case the same code would have appeared to work, which is the dangerous part. collect(Collectors.toList()) on the same data gave the right size, 100,000.
The rule has a name: the function passed to reduce must be associative and non-interfering. Associative means (a + b) + c equals a + (b + c), because a parallel stream may group elements any way it likes. Non-interfering means it does not change the stream's source or any shared object. Addition and max qualify. Mutating a shared list does not.
Bridge: primitive streams and the cost of boxing
A Stream<Integer> holds Integer objects. Each is a separate heap object of about 16 bytes, reached through a reference of 4 to 8 bytes, and arithmetic on it must unwrap it (unboxing) and wrap the result again (boxing). A plain int is just 4 bytes and needs none of that.
That is why Java has IntStream, LongStream and DoubleStream. They hold raw primitives, they have sum(), average(), min(), max() and summaryStatistics() built in, and they use the primitive functional interfaces from Fig. 21.4. You get to them with mapToInt, mapToLong, mapToDouble, or from IntStream.range. You get back to objects with boxed() or mapToObj.
Idiom: primitive streams for numbers
The problem: a pipeline sums order totals with map(...).reduce(0, Integer::sum). It works and passes every test, but it creates and unwraps millions of Integer objects.
How it works: switch to a primitive stream as early as you can. mapToInt(Order::totalCents) converts each order to a plain int, and from there sum() runs on primitives. If the numbers were never objects in the first place (a int[]), Arrays.stream(array) skips even the first conversion.
- Numbers out of objects:
mapToInt,mapToLongormapToDouble. - Aggregate on the primitive stream:
sum(),max(),average(),summaryStatistics(). - Need objects again:
boxed()ormapToObj, as late as possible.
Make the invisible visible: the same total over 5,000,000 numbers from new Random(42), computed three ways. The program runs each way seven times, so the first runs warm up the JIT compiler, and prints the fastest.
import java.util.*;
import java.util.stream.*;
public class Boxing {
static long best(Runnable r) {
long best = Long.MAX_VALUE;
for (int i = 0; i < 7; i++) { // first runs also warm up the JIT
long t0 = System.nanoTime();
r.run();
best = Math.min(best, System.nanoTime() - t0);
}
return best / 1_000_000;
}
public static void main(String[] args) {
Random rnd = new Random(42);
int[] arr = new int[5_000_000];
for (int i = 0; i < arr.length; i++) arr[i] = rnd.nextInt(100);
List<Integer> boxed = Arrays.stream(arr).boxed().toList();
long[] sink = new long[3];
long a = best(() -> sink[0] = boxed.stream().map(x -> x * 2).reduce(0, Integer::sum));
long b = best(() -> sink[1] = boxed.stream().mapToInt(x -> x * 2).sum());
long c = best(() -> sink[2] = Arrays.stream(arr).map(x -> x * 2).sum());
System.out.println("same answer : " + sink[0] + " " + sink[1] + " " + sink[2]);
System.out.println("List<Integer> map+reduce(Integer::sum): " + a + " ms");
System.out.println("List<Integer> mapToInt+sum : " + b + " ms");
System.out.println("int[] IntStream map+sum : " + c + " ms");
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}same answer : 495216952 495216952 495216952
List<Integer> map+reduce(Integer::sum): 65 ms
List<Integer> mapToInt+sum : 5 ms
int[] IntStream map+sum : 2 ms
// measured on the course machine (12 cores); your numbers will differAll three give the same answer, 495,216,952. The times differ by a lot: 65 ms for map + reduce(Integer::sum) on a List<Integer>, 5 ms for mapToInt + sum on the same list, and 2 ms for an IntStream on a plain int[]. So the primitive stream is about 13 times faster here, and not boxing at all is roughly 30 times faster. These are timings on one machine, so treat the ratios as the lesson and the milliseconds as a sample.
The reason has two parts. The boxed pipeline allocates a new Integer for every x * 2 result, which keeps the garbage collector busy. And the list stores references, so reading it jumps around memory, while an int[] is one continuous block that the CPU can read quickly.
- Works:
mapToInt(...).sum(),IntStream.range(...),summaryStatistics()for count, sum, min, max and average in one pass. - Fails:
reduce(0, Integer::sum)on millions of boxed values in hot code, andboxed()in the middle of a pipeline "just to use a generic method". For small collections the difference does not matter, so do not rewrite working code on a hunch. - Interview takeaway: "
Stream<Integer>boxes every element. For numeric work I convert withmapToIntormapToLongand usesum,averageorsummaryStatistics. On 5 million elements that was about 13 times faster in my measurement."
Bridge: toList() versus collect(toList())
Since Java 16, a stream has a short toList() method. It is not the same as collect(Collectors.toList()), and the difference matters when the result is passed around.
import java.util.*;
import java.util.stream.*;
public class ToListDemo {
public static void main(String[] args) {
List<String> a = Data.ORDERS.stream().map(Order::customer).distinct().toList();
List<String> b = Data.ORDERS.stream().map(Order::customer).distinct().collect(Collectors.toList());
System.out.println("toList() : " + a + " class = " + a.getClass().getSimpleName());
System.out.println("collect(toList()) : " + b + " class = " + b.getClass().getSimpleName());
try { a.add("zed"); } catch (UnsupportedOperationException e) { System.out.println("toList().add -> " + e); }
b.add("zed");
System.out.println("collect(toList()).add worked: " + b);
// toList() also allows null elements, Stream.toList and List.of differ here
List<String> withNull = Stream.of("a", null, "c").toList();
System.out.println("toList with null : " + withNull);
try { List.of("a", null); } catch (NullPointerException e) { System.out.println("List.of with null -> NullPointerException"); }
List<String> unmod = Stream.of("x", "y").collect(Collectors.toUnmodifiableList());
try { unmod.add("z"); } catch (UnsupportedOperationException e) { System.out.println("toUnmodifiableList.add -> UnsupportedOperationException"); }
}
}toList() : [asha, ravi, meera, kiran] class = ListN
collect(toList()) : [asha, ravi, meera, kiran] class = ArrayList
toList().add -> java.lang.UnsupportedOperationException
collect(toList()).add worked: [asha, ravi, meera, kiran, zed]
toList with null : [a, null, c]
List.of with null -> NullPointerException
toUnmodifiableList.add -> UnsupportedOperationExceptionRead the first four lines. toList() gave an unmodifiable list (class ListN, an internal type), and add threw UnsupportedOperationException. collect(Collectors.toList()) gave an ArrayList that accepted add. The documentation does not promise that Collectors.toList() returns an ArrayList or that it is mutable. It is only true today. Code that relies on it can break in a later release.
A subtle difference sits in the last lines. Stream.toList() allows null elements ([a, null, c]), while List.of(...) and Collectors.toUnmodifiableList() reject them. So toList() is "unmodifiable, but tolerant of null".
- Use
toList(): when you only read the result. It is shorter and states the intent. - Use
collect(Collectors.toCollection(ArrayList::new)): when you really need a mutable list. This is guaranteed, and it says so in the code. - Avoid
collect(Collectors.toList())when you later mutate the list: it works today only by accident of the implementation.
Idiom: no side effects inside a pipeline
The problem: a pipeline writes to something outside itself: forEach(list::add), map(x -> { counter++; return x; }), or a call that updates a shared map. It appears to work in a quick test.
How it works: the stream API assumes each step's lambda only reads its input and returns a result (it is non-interfering and, where it matters, stateless). The library is then free to run the steps in any order, on any thread, and skip them when the answer is known. A lambda that writes outside breaks that assumption. Sequentially, the bug stays hidden. In a parallel stream, the writes happen on many threads at once, and the result is wrong.
- Need a list or a map: end with
toList()orcollect(...). Let the stream own the container. - Need a number: end with
sum,count,reduceorsummarizingInt. - Really need an effect: keep it in the terminal
forEach(printing, sending a message), and make it safe to run on many threads.
Make the invisible visible: the same forEach(list::add) over 200,000 numbers, once sequentially and three times in parallel, against a stream that builds the list itself.
import java.util.*;
import java.util.stream.*;
public class SideEffects {
public static void main(String[] args) {
List<Integer> ids = IntStream.rangeClosed(1, 200_000).boxed().toList();
// Sequential: appears to work
List<Integer> seq = new ArrayList<>();
ids.stream().filter(i -> i % 2 == 0).forEach(seq::add);
System.out.println("sequential forEach(add): size = " + seq.size() + " (expected 100000)");
// Parallel: the same code, three runs
for (int run = 1; run <= 3; run++) {
List<Integer> par = new ArrayList<>();
try {
ids.parallelStream().filter(i -> i % 2 == 0).forEach(par::add);
System.out.println("parallel forEach(add): size = " + par.size() + " (expected 100000)");
} catch (Exception e) {
System.out.println("parallel forEach(add): " + e.getClass().getSimpleName());
}
}
// The fix: let the stream build the list
List<Integer> fixed = ids.parallelStream().filter(i -> i % 2 == 0).toList();
System.out.println("parallel toList() : size = " + fixed.size());
}
}sequential forEach(add): size = 100000 (expected 100000)
parallel forEach(add): size = 48256 (expected 100000)
parallel forEach(add): size = 71977 (expected 100000)
parallel forEach(add): size = 35503 (expected 100000)
parallel toList() : size = 100000Sequentially the list has 100,000 elements, as expected. In parallel, the three runs ended with 48,256, 71,977 and 35,503 elements: more than half of the data was lost, and the number is different every time. Nothing threw an error. (Other runs can end with an ArrayIndexOutOfBoundsException when two threads grow the internal array together, as the reduce example earlier did.) ArrayList is not safe for several writers. The last line, toList() on the same parallel stream, is correct, because each thread gets its own buffer and the library merges them.
This is the same bug as the Friday report in section 07, but there the shared object is a HashMap. A stream with side effects will pass a unit test on three orders and fail on three million.
- Works:
toList(),collect,reduce, and a terminalforEachthat only prints or sends. - Fails:
forEach(shared::add), counters changed insidemaporfilter, any write to a field or map from inside an intermediate step. Alsopeekused for real work, which may be skipped (thecount()surprise). - Interview takeaway: "Lambdas in a stream should be pure: read the input, return a result. Collecting into an outside list works by luck when sequential and loses data when parallel. I let
collectortoListbuild the result."
Bridge: takeWhile and dropWhile versus filter
Java 9 added takeWhile and dropWhile. They look like filters, but they use the condition differently. filter(p) tests every element. takeWhile(p) keeps elements from the start and stops at the first one that fails. dropWhile(p) throws away elements from the start until the first one fails, then keeps everything after it.
On sorted data, takeWhile is a faster filter, because the first failure means all the rest fail too. On unsorted data it gives a different, usually wrong, answer. The program runs both on the sorted and the unsorted order totals.
import java.util.*;
import java.util.stream.*;
public class TakeWhileDemo {
static int looked;
public static void main(String[] args) {
// order totals, already sorted ascending
List<Integer> totals = Data.ORDERS.stream().map(Order::totalCents).sorted().toList();
System.out.println("sorted totals : " + totals);
looked = 0;
List<Integer> viaFilter = totals.stream().peek(t -> looked++).filter(t -> t < 30000).toList();
System.out.println("filter(< 30000) : " + viaFilter + " looked at " + looked);
looked = 0;
List<Integer> viaTake = totals.stream().peek(t -> looked++).takeWhile(t -> t < 30000).toList();
System.out.println("takeWhile(< 30000) : " + viaTake + " looked at " + looked);
looked = 0;
List<Integer> viaDrop = totals.stream().peek(t -> looked++).dropWhile(t -> t < 30000).toList();
System.out.println("dropWhile(< 30000) : " + viaDrop + " looked at " + looked);
// the trap: on UNSORTED data takeWhile stops at the first miss
List<Integer> unsorted = Data.ORDERS.stream().map(Order::totalCents).toList();
System.out.println("unsorted totals : " + unsorted);
System.out.println("takeWhile(< 30000) : " + unsorted.stream().takeWhile(t -> t < 30000).toList());
System.out.println("filter(< 30000) : " + unsorted.stream().filter(t -> t < 30000).toList());
}
}sorted totals : [21900, 23800, 24900, 27400, 27600, 29700, 34900, 46900, 54700, 68700, 79800, 89400]
filter(< 30000) : [21900, 23800, 24900, 27400, 27600, 29700] looked at 12
takeWhile(< 30000) : [21900, 23800, 24900, 27400, 27600, 29700] looked at 7
dropWhile(< 30000) : [34900, 46900, 54700, 68700, 79800, 89400] looked at 12
unsorted totals : [54700, 29700, 21900, 46900, 27400, 24900, 79800, 27600, 89400, 34900, 23800, 68700]
takeWhile(< 30000) : []
filter(< 30000) : [29700, 21900, 27400, 24900, 27600, 23800]On the sorted data, both give the same six totals under 30,000. But filter looked at all 12 elements and takeWhile looked at 7: the six hits plus the one failure that told it to stop. On the unsorted data, the very first total is 54,700, which fails the test, so takeWhile returned an empty list while filter correctly found six. Use takeWhile only when the order guarantees "once false, always false".
A loop and a stream, side by side
To finish the section, here is one question answered both ways: "what is the revenue of delivered orders in Bengaluru?" By hand: orders 1, 2, 4, 6 and 8 are delivered in Bengaluru (orders 10 and 12 are cancelled or still preparing). Their totals are 54,700 + 29,700 + 46,900 + 24,900 + 27,600 = 183,800 paise, which is Rs 1,838.00.
for loop
Say how: a counter, a loop, an if and an update.
int total = 0;
for (Order o : orders) {
if (o.city().equals("Bengaluru")
&& o.status().equals(
"DELIVERED")) {
total += o.totalCents();
}
}Stream
Say what: keep these, take this number, add.
int total = orders.stream()
.filter(o -> o.city()
.equals("Bengaluru"))
.filter(o -> o.status()
.equals("DELIVERED"))
.mapToInt(Order::totalCents)
.sum();The shift: the loop describes the steps of the computer, the stream describes the question. Neither is faster in this example, and both are correct.
import java.util.*;
import java.util.stream.*;
public class LoopVsStream {
public static void main(String[] args) {
// for loop
int loopTotal = 0;
for (Order o : Data.ORDERS) {
if (o.city().equals("Bengaluru") && o.status().equals("DELIVERED")) {
loopTotal += o.totalCents();
}
}
// stream
int streamTotal = Data.ORDERS.stream()
.filter(o -> o.city().equals("Bengaluru"))
.filter(o -> o.status().equals("DELIVERED"))
.mapToInt(Order::totalCents)
.sum();
System.out.println("loop : " + loopTotal + " paise = Rs " + loopTotal / 100.0);
System.out.println("stream : " + streamTotal + " paise = Rs " + streamTotal / 100.0);
}
}loop : 183800 paise = Rs 1838.0
stream : 183800 paise = Rs 1838.0Both print 183,800 paise, which matches the hand calculation. A stream is not automatically better. Streams read well when the job is "filter, transform, collect". They read badly when the job is control flow. Use the table to decide.
| Situation | Why a loop wins | The stream workaround, and its cost |
|---|---|---|
| Return early from the method | return inside a loop leaves the method. A lambda's return only leaves the lambda. | anyMatch or findFirst, which are fine for yes/no but awkward for anything else. |
| The body throws a checked exception | A lambda for Function cannot throw IOException. A loop body can. | Wrap in a helper that converts to UncheckedIOException. Noise in every step. |
| You need the index | for (int i = 0; ...) gives i and i - 1 directly. | IntStream.range(0, n).mapToObj(...). Longer than the loop. |
| Update several local variables | Lambdas cannot change locals (effectively final rule from section 04). | Arrays of one element, or a collector. Both worse to read. |
break or continue with a label, or a state machine | Control flow is the point. | takeWhile covers only the simplest break. |
| Tiny collections in very hot code | A stream allocates a few objects. A loop allocates none. | Only matters when profiling says so. |
A good working rule: if you can say the job in one sentence with the verbs "keep", "turn into", "group" or "total", write a stream. If you have to say "go through each, and if..., then break out, but remember...", write a loop. Using a stream for something that wants a loop is a way to lose readability without gaining anything.
That finishes how a single pipeline runs. Section 06 looks at the most powerful terminal operation, collect, and the collectors that group, split and summarise your data.
06 · CollectorsCollectors: Grouping, Partitioning, toMap and Teeing
A collector is the recipe that collect uses to turn a stream into a result: a list, a map, a count, a summary. The built-in collectors in java.util.stream.Collectors cover most reports you will ever write. The main ideas are a classifier that chooses a bucket, a downstream collector that summarises each bucket, and teeing to compute two things in one pass. You will also learn which collector calls crash on duplicate keys, and the newest tool, gatherers.
QuickBite's "orders per customer" report was one line of code, and it worked in every test. The developer wanted a map from customer name to number of orders, so they wrote toMap(Order::customer, o -> 1): the key is the customer, the value is 1 for each order. They forgot that customers order more than once.
In production, the first customer with a second order took the endpoint down. Here it is with the sample data, where "asha" has ordered four times.
import java.util.*;
import java.util.stream.*;
public class ToMapDup {
public static void main(String[] args) {
try {
Map<String, Integer> m = Data.ORDERS.stream()
.collect(Collectors.toMap(Order::customer, o -> 1));
} catch (IllegalStateException e) {
System.out.println(e);
}
// Fix 1: a merge function says what to do with two values for the same key
Map<String, Integer> perCustomer = Data.ORDERS.stream()
.collect(Collectors.toMap(Order::customer, o -> 1, Integer::sum));
System.out.println("merge Integer::sum : " + perCustomer + " (" + perCustomer.getClass().getSimpleName() + ")");
// Fix 2: a map supplier decides the map type, so the order is predictable
Map<String, Integer> ordered = Data.ORDERS.stream()
.collect(Collectors.toMap(Order::customer, o -> 1, Integer::sum, LinkedHashMap::new));
System.out.println("LinkedHashMap::new (first seen): " + ordered);
Map<String, Integer> sorted = Data.ORDERS.stream()
.collect(Collectors.toMap(Order::customer, Order::totalCents, Integer::sum, TreeMap::new));
System.out.println("spend per customer, TreeMap : " + sorted);
// keep the first / keep the last
Map<String, Integer> firstTotal = Data.ORDERS.stream()
.collect(Collectors.toMap(Order::customer, Order::totalCents, (a, b) -> a, LinkedHashMap::new));
Map<String, Integer> lastTotal = Data.ORDERS.stream()
.collect(Collectors.toMap(Order::customer, Order::totalCents, (a, b) -> b, LinkedHashMap::new));
System.out.println("first order total (a, b) -> a: " + firstTotal);
System.out.println("last order total (a, b) -> b: " + lastTotal);
// the second trap: toMap does not allow null values
try {
Stream.of("a", "b").collect(Collectors.toMap(s -> s, s -> (String) null));
} catch (NullPointerException e) {
System.out.println("null value -> NullPointerException");
}
}
}java.lang.IllegalStateException: Duplicate key asha (attempted merging values 1 and 1)
merge Integer::sum : {meera=3, kiran=2, asha=4, ravi=3} (HashMap)
LinkedHashMap::new (first seen): {asha=4, ravi=3, meera=3, kiran=2}
spend per customer, TreeMap : {asha=197900, kiran=116800, meera=125500, ravi=89500}
first order total (a, b) -> a: {asha=54700, ravi=29700, meera=21900, kiran=27400}
last order total (a, b) -> b: {asha=68700, ravi=34900, meera=23800, kiran=89400}
null value -> NullPointerExceptionThe first line is the production crash:
IllegalStateException: Duplicate key asha (attempted merging values 1 and 1)The message even gives the two values it failed to merge. A plain toMap assumes every key is unique, and throws on the second one.
Idiom: toMap always gets a merge function
The problem: toMap(keyFn, valueFn) has no plan for two elements with the same key. It crashes, but only when the data finally contains a duplicate, which may be months after the code shipped.
How it works: the three-argument form toMap(keyFn, valueFn, mergeFn) says what to do on a clash. The merge function receives the old value and the new value and returns the one to keep. The four-argument form adds a Supplier for the map itself, which decides the map type (and so the order).
- Counting or summing: merge with
Integer::sum. Here it gaveasha=4, ravi=3, meera=3, kiran=2. - Keep the first:
(a, b) -> a. Keep the last:(a, b) -> b. The output shows asha's first total, 54,700, against her last, 68,700. - Predictable order: add
LinkedHashMap::new(insertion order) orTreeMap::new(sorted by key) as the fourth argument. The default is aHashMap, whose order looks random and may change between Java versions. - If duplicates are really a bug: keep the two-argument form, so that the crash tells you. But then catch it in a test, not in production.
One more trap in the last line of the output: toMap throws NullPointerException when a value is null, because it uses HashMap.merge internally. If a value can be missing, replace it with a default before collecting, or use groupingBy.
- Works:
toMap(Order::customer, o -> 1, Integer::sum)for counts,toMap(k, v, (a, b) -> a)for "any one is fine", and a map supplier whenever the order of the printed result matters. - Fails: the two-argument form on data that can repeat a key. Null values. Assuming the result is sorted or in insertion order without asking for it.
- Interview takeaway: "Plain
toMapthrowsIllegalStateException: Duplicate key. I pass a merge function, for exampleInteger::sum, and a map supplier likeLinkedHashMap::newwhen order matters."
For counting, though, toMap with o -> 1 is the long way around. The right tool is groupingBy with a counting collector, and the next bridge explains it.
Bridge: groupingBy, one level down
You know GROUP BY from SQL. groupingBy is the same idea with two steps, shown in Fig. 21.8. First, a classifier function (Order::restaurant) looks at each element and returns its key, which picks a bucket in a map. Second, a downstream collector decides what to keep in each bucket. If you give none, the default is toList(), so every bucket holds a list of whole orders.
groupingBy(Order::restaurant, summingInt(Order::totalCents)). The classifier chooses the bucket and the downstream collector shrinks each bucket to one number, so the lists of orders are never stored.The numbers in the figure come from the real run in the next program. Spice Hut has five orders (1, 3, 6, 9, 12) and its total is 259,600 paise, which includes the cancelled order 3 and the preparing order 12. Whether to exclude those is a business question; a filter before collect would do it.
Idiom: summarise inside groupingBy with a downstream collector
The problem: the report groups orders into lists and then loops over the lists to count or sum. Every order is kept in memory, and the code has two steps where one would do.
How it works: the second argument of groupingBy is a collector applied to each bucket. counting(), summingInt(f), averagingInt(f), mapping(f, toSet()), maxBy(c) and summarizingInt(f) turn each bucket into a single result. The third form, groupingBy(classifier, mapFactory, downstream), also picks the map type, so TreeMap::new gives sorted keys.
- Pick the key: a function from element to key (
Order::restaurant). - Pick the question for each bucket: count, sum, average, distinct values, biggest.
- Pick the map: default
HashMap, orTreeMap::newfor sorted keys.
Make the invisible visible: first the version without a downstream collector (a map of lists, then a second loop), then the same answer with summingInt.
import java.util.*;
import java.util.stream.*;
public class GroupingNoDownstream {
public static void main(String[] args) {
// without a downstream collector: whole orders pile up in lists, then we loop AGAIN
Map<String, List<Order>> byRestaurant = Data.ORDERS.stream()
.collect(Collectors.groupingBy(Order::restaurant));
Map<String, Integer> revenue = new TreeMap<>();
for (Map.Entry<String, List<Order>> e : byRestaurant.entrySet()) {
int sum = 0;
for (Order o : e.getValue()) sum += o.totalCents();
revenue.put(e.getKey(), sum);
}
System.out.println("lists kept in memory: " + byRestaurant.values().stream().mapToInt(List::size).sum() + " orders");
System.out.println("revenue : " + revenue);
// with a downstream collector: only the running sum is kept
System.out.println("downstream : " + new TreeMap<>(Data.ORDERS.stream().collect(
Collectors.groupingBy(Order::restaurant, Collectors.summingInt(Order::totalCents)))));
}
}lists kept in memory: 12 orders
revenue : {Dosa Corner=108500, Pizza Lane=161600, Spice Hut=259600}
downstream : {Dosa Corner=108500, Pizza Lane=161600, Spice Hut=259600}Both give the same three totals. The first version held all 12 orders in lists before adding them up (the first printed line). The second version never stored an order, it kept only a running int per restaurant. With 12 orders that does not matter. With 20 million orders it is the difference between a few kilobytes and several gigabytes. Now the full toolbox on the twelve orders.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class GroupingDemo {
public static void main(String[] args) {
var orders = Data.ORDERS;
System.out.println("grouping only (values are lists of whole orders):");
Map<String, List<Integer>> ids = orders.stream()
.collect(groupingBy(Order::restaurant, mapping(Order::id, toList())));
System.out.println(" order ids per restaurant : " + ids);
System.out.println("orders per restaurant : " + orders.stream()
.collect(groupingBy(Order::restaurant, counting())));
System.out.println("revenue paise per restaurant : " + orders.stream()
.collect(groupingBy(Order::restaurant, summingInt(Order::totalCents))));
System.out.println("customers per city : " + orders.stream()
.collect(groupingBy(Order::city, TreeMap::new, mapping(Order::customer, toCollection(TreeSet::new)))));
System.out.println("average order paise per city : " + orders.stream()
.collect(groupingBy(Order::city, averagingInt(Order::totalCents))));
System.out.println("sorted keys (TreeMap::new) : " + orders.stream()
.collect(groupingBy(Order::status, TreeMap::new, counting())));
System.out.println("biggest order per restaurant : " + orders.stream()
.collect(groupingBy(Order::restaurant, TreeMap::new,
maxBy(Comparator.comparingInt(Order::totalCents)))).entrySet().stream()
.map(e -> e.getKey() + "=#" + e.getValue().get().id()).toList());
IntSummaryStatistics st = orders.stream().collect(summarizingInt(Order::totalCents));
System.out.println("summarizingInt : " + st);
}
}grouping only (values are lists of whole orders):
order ids per restaurant : {Spice Hut=[1, 3, 6, 9, 12], Dosa Corner=[2, 5, 8, 11], Pizza Lane=[4, 7, 10]}
orders per restaurant : {Spice Hut=5, Dosa Corner=4, Pizza Lane=3}
revenue paise per restaurant : {Spice Hut=259600, Dosa Corner=108500, Pizza Lane=161600}
customers per city : {Bengaluru=[asha, ravi], Mysuru=[kiran, meera]}
average order paise per city : {Bengaluru=41057.142857142855, Mysuru=48460.0}
sorted keys (TreeMap::new) : {CANCELLED=2, DELIVERED=8, PREPARING=2}
biggest order per restaurant : [Dosa Corner=#2, Pizza Lane=#7, Spice Hut=#9]
summarizingInt : IntSummaryStatistics{count=12, sum=529700, min=21900, average=44141.666667, max=89400}Walk through the output. Order ids per restaurant shows the buckets from Fig. 21.8, with mapping keeping just the ids. Orders per restaurant is counting: 5, 4 and 3.
Customers per city used mapping(Order::customer, toCollection(TreeSet::new)) to get sorted unique names: Bengaluru has asha and ravi, Mysuru has kiran and meera. Average order value per city is averagingInt: Bengaluru 41,057.14 paise over 7 orders, Mysuru 48,460 paise over 5.
The TreeMap::new line puts the keys in alphabetical order. And summarizingInt returns count, sum, min, average and max in a single pass: 12 orders, 529,700 paise, cheapest 21,900, dearest 89,400.
- Works:
groupingBy(key, counting()),groupingBy(key, summingInt(f)),groupingBy(key, TreeMap::new, mapping(f, toList())). NestedgroupingByfor two-level tables (see the dashboard below). - Fails: grouping into lists and then looping to total them. Also forgetting that the default map is unordered, and that
averagingIntreturns adoubleeven when you hoped for whole numbers. - Interview takeaway: "
groupingByhas a classifier and a downstream collector. I summarise inside it withcounting,summingIntormapping, so I never hold the groups as lists, and I passTreeMap::newwhen I want sorted keys."
Bridge: partitioningBy, joining, filtering, flatMapping and friends
partitioningBy(predicate) is groupingBy with a yes/no classifier. The result map has exactly two keys, true and false, and both are always present, even when one side is empty. With groupingBy an empty group simply has no key. That small difference makes partitioningBy safer when you later call map.get(true).
The program below also uses five more collectors that you will meet in real code. They are worth knowing by name.
joining(delimiter, prefix, suffix): glue strings into one, for logs and CSV rows.filtering(predicate, downstream)(Java 9): filter inside a group. A group whose members all fail still appears, with an empty result such as 0.flatMapping(f, downstream)(Java 9): flatten inside a group, for example every item sold by each restaurant.collectingAndThen(downstream, finisher): collect, then transform the result once, for example wrap the list as unmodifiable.toUnmodifiableList/Set/Map(Java 10): the result rejects changes and rejectsnull.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class CollectorsMore {
public static void main(String[] args) {
var orders = Data.ORDERS;
System.out.println("partitioningBy delivered : " + orders.stream()
.collect(partitioningBy(o -> o.status().equals("DELIVERED"), counting())));
System.out.println("partition, whole lists : " + orders.stream()
.collect(partitioningBy(o -> o.totalCents() > 50000, mapping(Order::id, toList()))));
System.out.println("groupingBy a boolean : " + orders.stream()
.limit(3).collect(groupingBy(o -> o.totalCents() > 50000, counting())));
System.out.println(" (note: partitioningBy on an EMPTY input still has BOTH keys:)");
System.out.println(" " + orders.stream().limit(0)
.collect(partitioningBy(o -> true, counting())));
System.out.println("joining : " + orders.stream().limit(4)
.map(Order::customer).distinct().collect(joining(", ", "[", "]")));
System.out.println("filtering (9) downstream : " + orders.stream().collect(
groupingBy(Order::restaurant, TreeMap::new, filtering(o -> o.status().equals("DELIVERED"), counting()))));
System.out.println(" vs filter() first : " + orders.stream()
.filter(o -> o.status().equals("CANCELLED")).collect(groupingBy(Order::restaurant, counting())));
System.out.println(" vs filtering() keeps empty groups: " + orders.stream().collect(
groupingBy(Order::restaurant, TreeMap::new, filtering(o -> o.status().equals("CANCELLED"), counting()))));
System.out.println("flatMapping (9) items : " + orders.stream().collect(
groupingBy(Order::restaurant, TreeMap::new,
flatMapping(o -> o.lines().stream().map(Line::item), toCollection(TreeSet::new)))));
List<String> frozen = orders.stream().map(Order::customer).distinct()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
System.out.println("collectingAndThen : " + frozen + " (unmodifiable)");
Map<Integer, String> byId = orders.stream().limit(3)
.collect(toUnmodifiableMap(Order::id, Order::customer));
try { byId.put(99, "x"); } catch (UnsupportedOperationException e) { System.out.println("toUnmodifiableMap(10) : put -> UnsupportedOperationException"); }
System.out.println(" " + new TreeMap<>(byId));
}
}partitioningBy delivered : {false=4, true=8}
partition, whole lists : {false=[2, 3, 4, 5, 6, 8, 10, 11], true=[1, 7, 9, 12]}
groupingBy a boolean : {false=2, true=1}
(note: partitioningBy on an EMPTY input still has BOTH keys:)
{false=0, true=0}
joining : [asha, ravi, meera]
filtering (9) downstream : {Dosa Corner=4, Pizza Lane=1, Spice Hut=3}
vs filter() first : {Spice Hut=1, Pizza Lane=1}
vs filtering() keeps empty groups: {Dosa Corner=0, Pizza Lane=1, Spice Hut=1}
flatMapping (9) items : {Dosa Corner=[filter coffee, idli, masala dosa, rava dosa], Pizza Lane=[coke, farmhouse, margherita], Spice Hut=[biryani, paneer tikka, raita]}
collectingAndThen : [asha, ravi, meera, kiran] (unmodifiable)
toUnmodifiableMap(10) : put -> UnsupportedOperationException
{1=asha, 2=ravi, 3=meera}The first two lines are partitioningBy: 8 delivered and 4 not, and the second shows order ids on each side (orders over Rs 500 are 1, 7, 9 and 12). The "EMPTY input" line proves the rule: {false=0, true=0}, both keys present, with no data at all.
The filtering lines show why a downstream filter exists. Filtering first (filter(...) then groupingBy) gave only Spice Hut and Pizza Lane, since only they have cancelled orders. Filtering inside the group kept all three restaurants and showed Dosa Corner=0. If a report must list every restaurant, even those with zero, use the downstream version.
Bridge: teeing, two answers in one pass
A stream can be used only once, but a report often wants two answers: the lowest and the highest total, or the sum and the count. The usual workaround is to build the stream twice, which reads the data twice and, for a database cursor or a file, may not even be possible. Java 12 added teeing to solve it. It sends each element to two collectors at the same time and then combines their two results with a function. The name comes from the T-shaped pipe fitting.
Idiom: teeing for two results in one pass
The problem: "show the cheapest and the dearest order" is written as two separate pipelines. Each one reads the whole source, and the code repeats the stream setup.
How it works: teeing(collectorA, collectorB, merger) feeds every element into both collectors during one pass. When the stream ends, merger receives both finished results and builds the final value, often a small record.
- Pick two collectors: for example
minByandmaxBy, orsummingIntandcounting. - Write the merger: a function of two arguments that returns the final result (a record, a string, a number).
- Collect once:
stream.collect(teeing(a, b, merger)).
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class TeeingDemo {
record MinMax(int min, int max) {}
public static void main(String[] args) {
// two passes: the stream is consumed twice, so it must be rebuilt
int min = Data.ORDERS.stream().mapToInt(Order::totalCents).min().getAsInt();
int max = Data.ORDERS.stream().mapToInt(Order::totalCents).max().getAsInt();
System.out.println("two passes : min=" + min + " max=" + max);
// one pass with teeing (12)
MinMax mm = Data.ORDERS.stream().collect(teeing(
minBy(Comparator.comparingInt(Order::totalCents)),
maxBy(Comparator.comparingInt(Order::totalCents)),
(lo, hi) -> new MinMax(lo.get().totalCents(), hi.get().totalCents())));
System.out.println("one pass : " + mm);
// average = sum / count, both from the SAME pass
double avg = Data.ORDERS.stream().collect(teeing(
summingInt(Order::totalCents), counting(), (sum, n) -> (double) sum / n));
System.out.println("average : " + avg + " paise");
// delivered and cancelled revenue side by side
var split = Data.ORDERS.stream().collect(teeing(
filtering(o -> o.status().equals("DELIVERED"), summingInt(Order::totalCents)),
filtering(o -> o.status().equals("CANCELLED"), summingInt(Order::totalCents)),
(kept, lost) -> "delivered=" + kept + " cancelled=" + lost));
System.out.println("revenue : " + split);
}
}two passes : min=21900 max=89400
one pass : MinMax[min=21900, max=89400]
average : 44141.666666666664 paise
revenue : delivered=324400 cancelled=56800Both approaches find min 21,900 and max 89,400. The average line is worth checking: 529,700 paise over 12 orders is 44,141.67, and the program got it from a single pass with summingInt and counting. The last line shows an elegant use, filtering inside each branch, to total delivered revenue (324,400) and cancelled revenue (56,800) side by side.
Since teeing arrived in Java 12, you can prove it with the compiler. This is the same tiny program, built for Java 11 and for Java 12.
$ javac --release 8 OptionalOr.java
OptionalOr.java:4: error: cannot find symbol
symbol: method or(()->Option[...]ack"))
$ javac --release 9 OptionalOr.java
(compiles)
$ javac --release 8 FilteringProof.java
FilteringProof.java:4: error: cannot find symbol
symbol: method filtering((x)->x > 2,Collector<Object,CAP#1,List<Object>>)
$ javac --release 9 FilteringProof.java
(compiles)
$ javac --release 11 TeeingProof.java
TeeingProof.java:4: error: cannot find symbol
symbol: method teeing(Collector<Object,CAP#1,Long>,Collector<Integer,CAP#2,Integer>,(n,s)->n +[...]" + s)
$ javac --release 12 TeeingProof.java
(compiles)
$ javac --release 15 MapMultiProof.java
MapMultiProof.java:4: error: cannot find symbol
symbol: method <Integer>mapMulti((x,sink)->[...]0); })
$ javac --release 16 MapMultiProof.java
(compiles)
$ javac --release 15 ToListProof.java
ToListProof.java:3: error: cannot find symbol
symbol: method toList()
$ javac --release 16 ToListProof.java
(compiles)With --release 11 the compiler cannot find teeing. With --release 12 it compiles. The same block also shows Optional.or and Collectors.filtering arriving in Java 9 and mapMulti and Stream.toList in Java 16. (The --release 8 compiles also print three "obsolete" warnings, which are real and removed here for space.)
- Works: min and max, sum and count (so, an average), delivered and cancelled totals, "the list and its size", all from one pass.
- Fails: using it when two independent streams would be clearer. Also returning
Optionalpieces fromminByand forgetting to unwrap them, as the merger above does withlo.get(). On an empty stream thatget()would throw, so check first. - Interview takeaway: "
teeing, since Java 12, runs two collectors over the same elements in one pass and merges the results with a function. I use it for min and max, or sum and count, so I do not have to read the source twice."
Bridge: top N per group
"The two best-selling items at each restaurant" is a common report and the first one that needs more than one collector call. There is no single built-in collector for it, so you build it in two steps. First, count the quantity of each item per restaurant with a nested groupingBy. Second, sort each restaurant's items by quantity, descending, and keep two.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class TopN {
public static void main(String[] args) {
// step 1: total quantity sold per (restaurant, item)
Map<String, Map<String, Integer>> qty = Data.ORDERS.stream()
.filter(o -> !o.status().equals("CANCELLED"))
.flatMap(o -> o.lines().stream().map(l -> Map.entry(o.restaurant(), l)))
.collect(groupingBy(Map.Entry::getKey, TreeMap::new,
groupingBy(e -> e.getValue().item(), TreeMap::new,
summingInt(e -> e.getValue().qty()))));
System.out.println("quantity per item : " + qty);
// step 2: per restaurant, keep the top 2 items by quantity
Map<String, List<String>> top2 = new TreeMap<>();
qty.forEach((restaurant, items) -> top2.put(restaurant, items.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.limit(2)
.map(e -> e.getKey() + " x" + e.getValue())
.toList()));
System.out.println("top 2 per restaurant: " + top2);
}
}quantity per item : {Dosa Corner={filter coffee=4, idli=4, masala dosa=5, rava dosa=2}, Pizza Lane={coke=2, farmhouse=2, margherita=1}, Spice Hut={biryani=7, paneer tikka=2, raita=4}}
top 2 per restaurant: {Dosa Corner=[masala dosa x5, filter coffee x4], Pizza Lane=[coke x2, farmhouse x2], Spice Hut=[biryani x7, raita x4]}Dosa Corner sold 5 masala dosas (orders 2 and 8: 3 + 2) and 4 filter coffees (order 5: 2, order 8: 2), tied with 4 idlis (order 5).
The sort has a tie-break by name, so "filter coffee" comes before "idli" and the top two are masala dosa and filter coffee. Without the tie-break, the result of a tie would depend on map order, and a report that changes between runs is a bug. Spice Hut's top two are biryani (2 + 1 + 3 + 1 = 7) and raita (1 + 3 = 4). Cancelled orders were excluded by the first filter.
Notice that the second step sorts only the items of one restaurant at a time, and each restaurant has a handful of items. That is cheap. Sorting a whole stream of millions of orders to find a top few would be wasteful (sorted is a barrier, as you saw in the trace).
A real report: the QuickBite daily dashboard
The next program is the one the operations team asked for: revenue by day and by restaurant, for delivered orders only, printed as a small table. It is one pipeline with a nested groupingBy, using TreeMap::new twice so that days and restaurants come out sorted. The printing code afterwards only formats.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Dashboard {
public static void main(String[] args) {
Map<String, Map<String, Integer>> table = Data.ORDERS.stream()
.filter(o -> o.status().equals("DELIVERED"))
.collect(groupingBy(Order::day, TreeMap::new,
groupingBy(Order::restaurant, TreeMap::new, summingInt(Order::totalCents))));
List<String> cols = List.of("Dosa Corner", "Pizza Lane", "Spice Hut");
System.out.printf("%-12s", "day");
cols.forEach(c -> System.out.printf("%13s", c));
System.out.printf("%13s%n", "TOTAL");
table.forEach((day, row) -> {
System.out.printf("%-12s", day);
cols.forEach(c -> System.out.printf("%13.2f", row.getOrDefault(c, 0) / 100.0));
System.out.printf("%13.2f%n", row.values().stream().mapToInt(i -> i).sum() / 100.0);
});
}
}day Dosa Corner Pizza Lane Spice Hut TOTAL
2026-11-28 297.00 0.00 547.00 844.00
2026-11-29 274.00 469.00 249.00 992.00
2026-11-30 514.00 0.00 894.00 1408.00Check one cell by hand. On 2026-11-29, Dosa Corner has delivered order 5 only: 4 × 4,900 + 2 × 3,900 = 27,400 paise, which is 274.00. Pizza Lane has order 4: 34,900 + 2 × 6,000 = 46,900, which is 469.00. The Spice Hut cell is order 6, 24,900 paise, which is 249.00. The row total is 992.00. A cell with no delivered orders shows 0.00 because of getOrDefault(c, 0).
Gatherers: your own intermediate operation (Java 24)
Collectors customise the end of a pipeline. Until Java 24 there was no way to customise the middle. If you wanted "group into windows of three" or "a running total", you had to leave the stream or write awkward code. Gatherers (JEP 485, final in Java 24) fix that. A Gatherer is a custom intermediate operation, applied with stream.gather(...), and the class Gatherers ships five ready-made ones.
windowFixed(n): chop the stream into lists of n, the last one possibly shorter.windowSliding(n): overlapping windows, each moving one step. Great for "this day compared with the day before".fold(initial, f): likereduce, but as an intermediate step that emits one result at the end.scan(initial, f): a running total. It emits the accumulated value after every element.mapConcurrent(max, f): runfon up tomaxelements at once, on virtual threads, and keep the order. A way to call a slow service for many elements.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class GatherersDemo {
public static void main(String[] args) {
// daily revenue of delivered orders, in rupees, in date order
List<Integer> daily = Data.ORDERS.stream()
.filter(o -> o.status().equals("DELIVERED"))
.collect(groupingBy(Order::day, TreeMap::new, summingInt(Order::totalCents)))
.values().stream().map(c -> c / 100).toList();
System.out.println("daily revenue (Rs) : " + daily);
var ids = Data.ORDERS.stream().map(Order::id);
System.out.println("windowFixed(3) : " + ids.gather(Gatherers.windowFixed(3)).toList());
System.out.println("windowSliding(2) : " + daily.stream().gather(Gatherers.windowSliding(2)).toList());
System.out.println(" day-over-day change : " + daily.stream().gather(Gatherers.windowSliding(2))
.map(w -> w.get(1) - w.get(0)).toList());
System.out.println("fold (sum, one result) : " + daily.stream()
.gather(Gatherers.fold(() -> 0, (acc, x) -> acc + x)).toList());
System.out.println("scan (running total) : " + daily.stream()
.gather(Gatherers.scan(() -> 0, (acc, x) -> acc + x)).toList());
long t0 = System.nanoTime();
List<Integer> mapped = IntStream.rangeClosed(1, 20).boxed()
.gather(Gatherers.mapConcurrent(10, i -> { sleep(100); return i * i; })).toList();
long ms = (System.nanoTime() - t0) / 1_000_000;
System.out.println("mapConcurrent(10) of 20 x 100 ms tasks: " + mapped.size() + " results in ~" + ms + " ms (sequential would be ~2000)");
}
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
}daily revenue (Rs) : [844, 992, 1408]
windowFixed(3) : [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
windowSliding(2) : [[844, 992], [992, 1408]]
day-over-day change : [148, 416]
fold (sum, one result) : [3244]
scan (running total) : [844, 1836, 3244]
mapConcurrent(10) of 20 x 100 ms tasks: 20 results in ~218 ms (sequential would be ~2000)The daily delivered revenue, in rupees, is 844, 992 and 1,408 for the three days. windowFixed(3) over the 12 order ids gave four windows of three. windowSliding(2) over the daily revenue gave the pairs [844, 992] and [992, 1408], and mapping each pair to the difference gave the day-over-day change, +148 and +416. fold reduced the whole stream to 3,244 in a single element. scan gave the running total 844, 1,836, 3,244.
The last line is the interesting one. mapConcurrent(10, ...) ran 20 tasks that each sleep 100 ms. Sequentially that would take about 2,000 ms. It took about 214 ms: twenty tasks, ten at a time, two waves of 100 ms. That is a fresh way to do concurrent I/O inside a stream without parallel streams and without the common-pool pitfall that you will see in section 07.
Gatherers were a preview feature in Java 22 and 23. You can prove the version boundary with the compiler: with --release 23 the call is rejected, with --release 24 it compiles.
GatherersDemo.java:15: error: Gatherers is a preview API and is disabled by default.
System.out.println("windowFixed(3) : " + ids.gather(Gatherers.windowFixed(3)).toList());
^
(use --enable-preview to enable preview APIs)
GatherersDemo.java:15: error: <R>gather(Gatherer<? super T,?,R>) is a preview API and is disabled by default.The second command printed nothing, which in javac means success. On Java 23 the message says Gatherers is a preview API and is disabled by default and tells you to add --enable-preview. Preview is explained in the Java versions part of this chapter. The practical rule: ship gatherers only if every environment runs Java 24 or later.
Bridge: a custom Collector, and why you rarely need one
When no built-in collector fits, Collector.of(...) builds one from four pieces. These are the same four pieces that a parallel collect uses internally, so knowing them also explains how the stream splits and merges the work.
- Supplier: make a fresh, empty container (
Stats::new). Called once per thread in a parallel stream. - Accumulator: put one element into a container.
- Combiner: merge two containers into one. Used only in parallel runs, but you must supply it.
- Finisher and characteristics (optional): turn the container into the final result, and tell the library hints such as
UNORDERED.
The program below builds a collector that tracks count, minimum, maximum and average of order totals, then compares it with the built-in IntSummaryStatistics.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class CustomCollector {
// the mutable "bucket" each thread fills
static class Stats {
int count, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
long sum;
void add(int x) { count++; sum += x; min = Math.min(min, x); max = Math.max(max, x); }
Stats merge(Stats o) {
count += o.count; sum += o.sum; min = Math.min(min, o.min); max = Math.max(max, o.max);
return this;
}
public String toString() { return "n=" + count + " min=" + min + " max=" + max + " avg=" + (double) sum / count; }
}
static Collector<Order, Stats, Stats> orderStats() {
return Collector.of(
Stats::new, // 1. supplier: a new empty bucket
(s, o) -> s.add(o.totalCents()), // 2. accumulator: put one element in
Stats::merge, // 3. combiner: join two buckets (parallel)
Collector.Characteristics.UNORDERED); // 4. (optional) hints
}
public static void main(String[] args) {
System.out.println("custom collector : " + Data.ORDERS.stream().collect(orderStats()));
System.out.println("same, parallel : " + Data.ORDERS.parallelStream().collect(orderStats()));
System.out.println("IntSummaryStats : " + Data.ORDERS.stream().mapToInt(Order::totalCents).summaryStatistics());
}
}custom collector : n=12 min=21900 max=89400 avg=44141.666666666664
same, parallel : n=12 min=21900 max=89400 avg=44141.666666666664
IntSummaryStats : IntSummaryStatistics{count=12, sum=529700, min=21900, average=44141.666667, max=89400}The custom collector gave the same numbers as summaryStatistics(): 12 orders, min 21,900, max 89,400, average 44,141.67. It also gave the same result in parallel, because the combiner joins partial results correctly. The built-in one did the whole thing in one line.
So when is writing your own worth it? Only when the result is a domain concept the library does not know (a "delivery performance score"), or when a pattern repeats in many reports. For plain statistics, IntSummaryStatistics already does the job. Before you write a collector, check whether teeing of two existing collectors would give you the same result in four lines.
Which tool for which job: collectors, a loop, or SQL
A collector runs inside your Java process, over data that is already in memory. That is the right place only when the data is small or already loaded. When the rows live in a database, pulling millions of them into Java just to group them is slow and wasteful. The database can group next to the data, using indexes, and send back a handful of rows.
| Option | Pick it when | Cost or catch |
|---|---|---|
stream + Collectors | Data is in memory, up to a few million rows. You group, count, sum and reshape. Readability matters. | All data must fit in the heap. Each collector is code you must test. Not parallel by default. |
Plain for loop | One pass, early exit, several mutable counters, or a hot inner loop measured to be slow. | More lines. Easy to forget a case. No built-in grouping. |
SQL GROUP BY in the database | The rows live in a database, or there are tens of millions. Indexes and the engine do the heavy part. | Logic lives in SQL, not Java. Harder to unit test. See Chapter E8. |
| Gatherers | Windows, running totals or concurrent mapping in the middle of a pipeline, Java 24 or later. | Newer API. Fewer people know it. Not available on Java 21. |
| A parallel stream (next section) | A very large in-memory collection with expensive per-element work. | Uses a shared pool, needs thread-safe code, and often is not faster. |
The dashboard from earlier is a good example. For 12 orders in memory, a stream is perfect. If the same report ran over a year of orders, you would not findAll() into a list. You would write a query like this and map the result rows:
SELECT day, restaurant, SUM(total) ... GROUP BY day, restaurantIn the next section the same pipelines get a .parallel() in front of them. Whether that makes things faster or breaks them depends on exactly what you have just learned: pure lambdas and the right collector.
07 · Parallel streamsParallel Streams: When They Help and When They Hurt
Adding .parallel() to a stream splits the data and runs the pieces on several CPU cores at once, using one shared pool of worker threads called the common pool. It can give a large speed-up for big, CPU-heavy, side-effect-free work, and it can make code slower or wrong in every other case. This section measures both outcomes on this machine, so you can decide with numbers instead of hope.
This is the Friday-dinner bug from the start of the chapter, measured. The "revenue by restaurant" endpoint was slow, so someone changed stream() to parallelStream() and kept the forEach that added into a shared HashMap. The code is tiny and looks harmless.
To make the demo big enough to show the damage, the program generates 2,000,000 synthetic sales with new Random(42), so every run sees the same data. It first computes the truth with a plain loop. Then it runs the shared-map version five times, and the correct groupingBy version five times.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class SharedMapRace {
record Sale(String restaurant, int cents) {}
static List<Sale> makeSales(int n) {
String[] names = {"Spice Hut", "Dosa Corner", "Pizza Lane"};
Random rnd = new Random(42);
List<Sale> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) list.add(new Sale(names[rnd.nextInt(3)], 10_000 + rnd.nextInt(90_000)));
return list;
}
public static void main(String[] args) {
List<Sale> sales = makeSales(2_000_000);
// the truth: a plain sequential loop
Map<String, Long> expected = new TreeMap<>();
for (Sale s : sales) expected.merge(s.restaurant(), (long) s.cents(), Long::sum);
long expectedAll = expected.values().stream().mapToLong(Long::longValue).sum();
System.out.println("expected : " + expected + " grand total " + expectedAll);
System.out.println("--- parallelStream().forEach into ONE shared HashMap, 5 runs:");
for (int run = 1; run <= 5; run++) {
Map<String, Long> shared = new HashMap<>();
try {
sales.parallelStream().forEach(s -> shared.merge(s.restaurant(), (long) s.cents(), Long::sum));
long all = shared.values().stream().mapToLong(Long::longValue).sum();
System.out.println("run " + run + ": grand total " + all + " wrong by " + (expectedAll - all) + " paise");
} catch (Exception e) {
System.out.println("run " + run + ": " + e.getClass().getName());
}
}
System.out.println("--- parallelStream().collect(groupingBy(...)), 5 runs:");
for (int run = 1; run <= 5; run++) {
Map<String, Long> fixed = new TreeMap<>(sales.parallelStream()
.collect(Collectors.groupingBy(Sale::restaurant, Collectors.summingLong(Sale::cents))));
System.out.println("run " + run + ": " + (fixed.equals(expected) ? "correct" : "WRONG") + " " + fixed);
}
}
}expected : {Dosa Corner=36644945363, Pizza Lane=36661280070, Spice Hut=36700293222} grand total 110006518655
--- parallelStream().forEach into ONE shared HashMap, 5 runs:
run 1: grand total 37515131320 wrong by 72491387335 paise
run 2: grand total 42066680846 wrong by 67939837809 paise
run 3: grand total 40370665969 wrong by 69635852686 paise
run 4: grand total 42299900957 wrong by 67706617698 paise
run 5: grand total 42548103895 wrong by 67458414760 paise
--- parallelStream().collect(groupingBy(...)), 5 runs:
run 1: correct {Dosa Corner=36644945363, Pizza Lane=36661280070, Spice Hut=36700293222}
run 2: correct {Dosa Corner=36644945363, Pizza Lane=36661280070, Spice Hut=36700293222}
run 3: correct {Dosa Corner=36644945363, Pizza Lane=36661280070, Spice Hut=36700293222}
run 4: correct {Dosa Corner=36644945363, Pizza Lane=36661280070, Spice Hut=36700293222}
run 5: correct {Dosa Corner=36644945363, Pizza Lane=36661280070, Spice Hut=36700293222}The truth is a grand total of 110,006,518,655 paise. Every shared-map run ended with a total around 40 billion: between 55% and 66% of the money was gone, and the figure was different on every run (37.5 to 42.5 billion in this batch, and from 40.3 to 49.6 billion in two more batches of five runs). No exception, no warning. The groupingBy version was correct in all five runs, and in the other batches too.
One honest note. The production report lost "a few thousand rupees", not 60%. That is what you see with a small number of orders and a lucky timing. Here there are 2 million orders, only three keys and twelve threads, so the threads collide almost all the time. The size of the damage depends on the data and the machine. The fact that it is wrong does not.
The week's other symptom, the ConcurrentModificationException, appears when the map has many keys and has to grow. This variant counts orders per customer for 100,000 different customers.
import java.util.*;
import java.util.stream.*;
public class SharedMapManyKeys {
public static void main(String[] args) {
Random rnd = new Random(42);
int[] customer = new int[2_000_000];
for (int i = 0; i < customer.length; i++) customer[i] = rnd.nextInt(100_000); // 100,000 different keys
Map<Integer, Integer> expected = new HashMap<>();
for (int c : customer) expected.merge(c, 1, Integer::sum);
System.out.println("expected: " + expected.size() + " customers, " + customer.length + " orders");
for (int run = 1; run <= 5; run++) {
Map<Integer, Integer> shared = new HashMap<>();
try {
Arrays.stream(customer).parallel().forEach(c -> shared.merge(c, 1, Integer::sum));
int all = shared.values().stream().mapToInt(Integer::intValue).sum();
System.out.println("run " + run + ": " + shared.size() + " keys, " + all + " orders counted (lost " + (customer.length - all) + ")");
} catch (Exception e) {
System.out.println("run " + run + ": " + e.getClass().getName());
}
}
}
}expected: 100000 customers, 2000000 orders
run 1: java.util.ConcurrentModificationException
run 2: java.util.ConcurrentModificationException
run 3: java.util.ConcurrentModificationException
run 4: java.util.ConcurrentModificationException
run 5: java.util.ConcurrentModificationExceptionAll five runs threw ConcurrentModificationException. HashMap keeps a counter of structural changes. When a thread resizes the table while another is in the middle of merge, the counter changes under it, and HashMap notices and throws. So there are two faces of one bug: with few keys the map silently loses updates, and with many keys it may throw. In neither case does it give a right answer.
Idiom: parallel streams share no mutable state
The problem: a parallel pipeline updates a shared HashMap, list, counter or other mutable object from inside forEach. Sequentially it is fine. In parallel, many threads write at once and the result is wrong or an exception is thrown.
How it works: collect gives each worker thread its own container (the supplier), lets it fill that container with no locks, and merges the containers at the end (the combiner). No two threads ever touch the same object, so nothing needs synchronisation. A shared object does the opposite: every thread fights over it.
- Let the stream build the answer:
collect(groupingBy(...)),toList(),sum(),reduce. - If you need a count or total, use the collector or
mapToLong().sum(), not a shared counter. - If you truly need a shared map, use a
ConcurrentHashMapand its atomicmerge. It is correct but slower, because threads compete for the same buckets.
Works: this code
parallel groupingruns offlineparallelStream().collect(groupingBy(Sale::restaurant, summingLong(Sale::cents)))was right in 5 of 5 runs in every batch, and equal to the sequential loop.
- Fails:
forEach(s -> map.merge(...))into aHashMap(wrong in 15 of 15 runs with 3 keys,ConcurrentModificationExceptionin 5 of 5 runs with 100,000 keys). Also sharedArrayList,int[]counters,StringBuilder. - Interview takeaway: "A parallel stream may run my lambda on twelve threads at once. So the lambda must not touch shared mutable state. I let
collectgive each thread its own container and merge them, which is correct without locks."
Bridge: how a parallel stream splits the work
When you call parallelStream(), nothing starts yet. The terminal operation starts the work, as always. What changes is how the source is cut up. Every source provides a Spliterator (a splittable iterator). Its key method, trySplit(), hands back the first half of the remaining elements and keeps the second half. Applying it again and again gives a tree of smaller and smaller pieces.
Each piece becomes a task for the fork-join framework, which is Java's engine for divide-and-conquer work. Tasks run on a pool of worker threads. If a worker has no tasks, it steals tasks from a busy worker, which keeps all cores busy even when the pieces are uneven. After the pieces finish, partial results are merged going back up the tree.
The picture was produced by the code below. This program takes a real ArrayList of 16 elements and calls trySplit() again and again, printing the tree. It stops at 2 elements to match the figure. The real library stops using a size heuristic that depends on the number of cores, so the actual tree is different, but the idea is the same.
import java.util.*;
import java.util.stream.*;
public class SplitTree {
static void split(Spliterator<Integer> sp, String indent, String label) {
System.out.println(indent + label + " size=" + sp.estimateSize());
Spliterator<Integer> left = sp.trySplit(); // returns the FIRST half, keeps the second
if (left == null) return;
if (sp.estimateSize() <= 2 && left.estimateSize() <= 2) { // stop at 2 elements (the real stop is a size heuristic)
System.out.println(indent + " leaf " + label + "-left : size=" + left.estimateSize());
System.out.println(indent + " leaf " + label + "-right: size=" + sp.estimateSize());
return;
}
split(left, indent + " ", label + "L");
split(sp, indent + " ", label + "R");
}
public static void main(String[] args) {
List<Integer> list = IntStream.rangeClosed(1, 16).boxed().toList();
split(list.spliterator(), "", "root");
System.out.println();
System.out.println("LinkedList 16 elements, first split gives: ");
Spliterator<Integer> sp = new LinkedList<>(list).spliterator();
Spliterator<Integer> left = sp.trySplit();
System.out.println(" left=" + left.estimateSize() + " right=" + sp.estimateSize() + " (a LinkedList copies a batch of 1024 into an array, or all if fewer)");
}
}root size=16
rootL size=8
rootLL size=4
leaf rootLL-left : size=2
leaf rootLL-right: size=2
rootLR size=4
leaf rootLR-left : size=2
leaf rootLR-right: size=2
rootR size=8
rootRL size=4
leaf rootRL-left : size=2
leaf rootRL-right: size=2
rootRR size=4
leaf rootRR-left : size=2
leaf rootRR-right: size=2
LinkedList 16 elements, first split gives:
left=16 right=0 (a LinkedList copies a batch of 1024 into an array, or all if fewer)The sizes are exactly what Fig. 21.9 shows: 16, then two 8s, four 4s and eight 2s. An ArrayList can split perfectly in half, because it knows its size and can jump to the middle. The last lines show a first sign of trouble: a LinkedList cannot find its middle without walking the list, so its Spliterator copies a batch of elements into an array, and splitting gives uneven halves. A LinkedList of 16 elements gave one piece of 16 and one of 0, so nothing was shared at all.
Make the invisible visible: which pool runs the pieces, and how many threads it has on this machine.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class CommonPool {
public static void main(String[] args) {
System.out.println("availableProcessors : " + Runtime.getRuntime().availableProcessors());
System.out.println("commonPool().getParallelism(): " + ForkJoinPool.commonPool().getParallelism());
Set<String> threads = ConcurrentHashMap.newKeySet();
IntStream.range(0, 1000).parallel().forEach(i -> {
threads.add(Thread.currentThread().getName());
try { Thread.sleep(1); } catch (InterruptedException e) { }
});
System.out.println("threads that did work : " + threads.size());
System.out.println(new TreeSet<>(threads));
}
}availableProcessors : 12
commonPool().getParallelism(): 11
threads that did work : 12
[ForkJoinPool.commonPool-worker-1, ForkJoinPool.commonPool-worker-10, ForkJoinPool.commonPool-worker-11, ForkJoinPool.commonPool-worker-2, ForkJoinPool.commonPool-worker-3, ForkJoinPool.commonPool-worker-4, ForkJoinPool.commonPool-worker-5, ForkJoinPool.commonPool-worker-6, ForkJoinPool.commonPool-worker-7, ForkJoinPool.commonPool-worker-8, ForkJoinPool.commonPool-worker-9, main]The machine has 12 cores, and ForkJoinPool.commonPool().getParallelism() is 11: always cores minus one. Why minus one? Because the thread that calls the terminal operation, here main, does a share of the work itself, which makes 12 threads at work. The set shows exactly that: commonPool-worker-1 to worker-11 plus main.
Two things follow, and both cause real incidents. First, the common pool is one pool per JVM. Every parallel stream in your application, in every library, and many CompletableFuture calls (section 11) share the same 11 workers. Second, you can resize it with -Djava.util.concurrent.ForkJoinPool.common.parallelism=N, but you are then resizing it for everything.
When a parallel stream helps: big, costly and independent
Parallel work has a fixed cost: splitting the source, handing tasks to other threads, waking those threads, and merging results. It only pays when the real work is larger than that cost. The classic case is a big range of numbers, each needing a lot of CPU. This program counts the primes below 2,000,000 with a simple trial-division test, sequentially and then in parallel.
Make the invisible visible: three rounds of both versions, after a warm-up so the JIT compiler has already compiled isPrime, then the best of the three rounds.
import java.util.stream.*;
public class PrimeSpeed {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; (long) d * d <= n; d++) if (n % d == 0) return false;
return true;
}
static long timeMs(Runnable r) {
long t0 = System.nanoTime();
r.run();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) {
long[] count = new long[2];
// warm-up so the JIT has compiled isPrime
IntStream.rangeClosed(1, 300_000).filter(PrimeSpeed::isPrime).count();
long bestSeq = Long.MAX_VALUE, bestPar = Long.MAX_VALUE;
for (int round = 1; round <= 3; round++) {
long seq = timeMs(() -> count[0] = IntStream.rangeClosed(1, 2_000_000).filter(PrimeSpeed::isPrime).count());
long par = timeMs(() -> count[1] = IntStream.rangeClosed(1, 2_000_000).parallel().filter(PrimeSpeed::isPrime).count());
System.out.printf("round %d: primes sequential=%d (%d ms) parallel=%d (%d ms) speed-up %.1fx%n",
round, count[0], seq, count[1], par, (double) seq / par);
bestSeq = Math.min(bestSeq, seq);
bestPar = Math.min(bestPar, par);
}
System.out.printf("best of 3: sequential %d ms, parallel %d ms, speed-up %.1fx%n", bestSeq, bestPar, (double) bestSeq / bestPar);
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}round 1: primes sequential=148933 (894 ms) parallel=148933 (166 ms) speed-up 5.4x
round 2: primes sequential=148933 (900 ms) parallel=148933 (172 ms) speed-up 5.2x
round 3: primes sequential=148933 (899 ms) parallel=148933 (165 ms) speed-up 5.4x
best of 3: sequential 894 ms, parallel 165 ms, speed-up 5.4x
// measured on the course machine (12 cores); your numbers will differBoth versions found the same 148,933 primes. The sequential version needed about 894 ms and the parallel one about 165 ms, a speed-up of 5.4 times on a machine with 12 cores. Why not 12 times? Part of the work cannot split (setting up, merging), the other programs running on this shared machine used some cores, and numbers near 2,000,000 take longer to test than small ones, so the pieces are uneven.
A note on how these numbers were obtained, because timing is easy to get wrong. This machine ran other Java programs at the same time. A first try gave sequential times from 977 to 2,346 ms, which is useless.
The program was run again three times, each time taking the best of three rounds, and the three results were within about 10% of each other (5.2x, 5.8x and 5.7x, then 5.4x in the run shown above). The lesson: measure several times, take the best of several, and know what else is running.
When a parallel stream hurts
Every one of the following looks like a harmless .parallel() and is slower, wrong or both. They are the cases an interviewer wants you to name.
Hurt 1: the list is small
For ten elements, the work takes 50 nanoseconds. Starting parallel tasks takes thousands of times longer than that. The program below sums 10 numbers 200,000 times, sequentially and in parallel.
import java.util.*;
import java.util.stream.*;
public class ParallelHurts {
static long best(int times, Runnable r) {
long best = Long.MAX_VALUE;
for (int i = 0; i < times; i++) {
long t0 = System.nanoTime();
r.run();
best = Math.min(best, System.nanoTime() - t0);
}
return best;
}
public static void main(String[] args) {
// 1. a tiny list: 10 elements, 200,000 calls each
List<Integer> tiny = IntStream.rangeClosed(1, 10).boxed().toList();
long[] sink = new long[1];
Runnable seqTiny = () -> { for (int i = 0; i < 200_000; i++) sink[0] += tiny.stream().mapToInt(x -> x).sum(); };
Runnable parTiny = () -> { for (int i = 0; i < 200_000; i++) sink[0] += tiny.parallelStream().mapToInt(x -> x).sum(); };
best(2, seqTiny); best(2, parTiny); // warm-up
long a = best(3, seqTiny), b = best(3, parTiny);
System.out.printf("1. sum of 10 elements : sequential %.2f us/call, parallel %.2f us/call (%.0fx slower)%n",
a / 200_000 / 1000.0, b / 200_000 / 1000.0, (double) b / a);
// 2. the same job over different SOURCES (2,000,000 elements, a little CPU work each)
int n = 2_000_000;
List<Integer> arrayList = IntStream.range(0, n).boxed().collect(Collectors.toCollection(ArrayList::new));
List<Integer> linked = new LinkedList<>(arrayList);
long[] r = new long[1];
java.util.function.ToLongFunction<Integer> work = x -> { long v = x; for (int i = 0; i < 40; i++) v = v * 31 + i; return v & 0xff; };
System.out.println("2. 2,000,000 elements, 40 multiplications each (best of 5):");
for (String name : List.of("ArrayList", "LinkedList", "Stream.iterate")) {
for (boolean par : new boolean[]{false, true}) {
Runnable job = () -> {
Stream<Integer> s = switch (name) {
case "ArrayList" -> arrayList.stream();
case "LinkedList" -> linked.stream();
default -> Stream.iterate(0, i -> i + 1).limit(n);
};
r[0] = (par ? s.parallel() : s).mapToLong(work).sum();
};
best(2, job);
long t = best(5, job) / 1_000_000;
System.out.printf(" %-15s %-10s %5d ms%n", name, par ? "parallel" : "sequential", t);
}
}
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
// 3. ordering: forEach versus forEachOrdered, findFirst versus findAny
System.out.print("3. parallel forEach : ");
IntStream.rangeClosed(1, 12).parallel().forEach(i -> System.out.print(i + " "));
System.out.print("\n parallel forEachOrdered : ");
IntStream.rangeClosed(1, 12).parallel().forEachOrdered(i -> System.out.print(i + " "));
System.out.println();
List<Integer> big = IntStream.rangeClosed(1, 1_000_000).boxed().toList();
System.out.print(" findFirst x5 : ");
for (int i = 0; i < 5; i++) System.out.print(big.parallelStream().filter(x -> x % 1000 == 0).findFirst().get() + " ");
System.out.print("\n findAny x5 : ");
for (int i = 0; i < 5; i++) System.out.print(big.parallelStream().filter(x -> x % 1000 == 0).findAny().get() + " ");
System.out.println();
}
}1. sum of 10 elements : sequential 0.06 us/call, parallel 8.28 us/call (136x slower)
2. 2,000,000 elements, 40 multiplications each (best of 5):
ArrayList sequential 51 ms
ArrayList parallel 7 ms
LinkedList sequential 48 ms
LinkedList parallel 18 ms
Stream.iterate sequential 72 ms
Stream.iterate parallel 50 ms
// measured on the course machine (12 cores); your numbers will differ
3. parallel forEach : 8 6 5 12 4 2 7 11 9 3 1 10
parallel forEachOrdered : 1 2 3 4 5 6 7 8 9 10 11 12
findFirst x5 : 1000 1000 1000 1000 1000
findAny x5 : 657000 657000 657000 657000 657000 The first line is the result: 0.06 microseconds per call sequentially, 8.28 microseconds in parallel, about 136 times slower. The parallel stream did nothing wrong. It simply paid a fixed price per call for work that was almost free. The same fixed price applies in a web endpoint that calls parallelStream() on a list of 20 items.
Hurt 2: the source splits badly
Block 2 of the output runs the same job (a few multiplications per element, 2,000,000 elements) over three sources. The best of five runs, in milliseconds, were these.
| Source | Sequential | Parallel | Speed-up | Why |
|---|---|---|---|---|
ArrayList | 51 ms | 7 ms | about 7x | Knows its size and splits exactly in the middle. |
LinkedList | 48 ms | 18 ms | about 2.7x | Must walk the list and copy batches into arrays to split. |
Stream.iterate(...).limit(n) | 72 ms | 50 ms | about 1.4x | Each element depends on the previous one, so the source is inherently sequential. |
The rule of thumb: arrays, ArrayList and IntStream.range split well. HashSet and TreeSet are medium. LinkedList, Stream.iterate and BufferedReader.lines() split poorly. If you have a poorly splitting source and a heavy job, copy it into an ArrayList first.
Hurt 3: ordering has a price
Block 3 of the output shows order. A parallel forEach printed 8 6 5 12 4 2 7 11 9 3 1 10, in whatever order the threads finished. forEachOrdered printed 1 to 12 in sequence, because it makes the threads wait for each other. That wait is a cost, and it can cancel the benefit of going parallel.
The same applies to findFirst against findAny. findFirst must return the first match in encounter order, so every thread has to check that no earlier piece has a match. findAny may return whichever match is found first by any thread.
In the run above, five runs of findFirst always gave 1000. Five runs of findAny gave 657000 each time, but an earlier run printed 657000, 516000, 657000, 657000, 657000: a different match, from a different thread.
So use findAny and forEach when you truly do not care about order, and limit on an ordered parallel stream is also costly, for the same reason.
Hurt 4: boxing
The boxing cost you measured in section 05 (65 ms against 5 ms) is paid on every worker thread. Parallel boxed streams also create more garbage, which the garbage collector must clean while the threads run. Use IntStream, LongStream and mapToInt first, and then parallelise.
Hurt 5: blocking calls in the common pool
This is the most damaging one in server code. A thread that sleeps or waits for the network does no useful work, and it cannot be used by anyone else. The common pool has only 11 workers, so 11 blocked tasks freeze every other user of the pool. The incident: an endpoint called a REST service for each of 50 items inside parallelStream().forEach.
The program simulates a REST call with a 100 ms sleep. It runs 50 calls in a parallel stream and in a virtual-thread executor (section 12 explains those). Then it measures a bystander: an unrelated supplyAsync task that only returns a string.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class BlockingPool {
static void callApi() { // pretend: a REST call that waits 100 ms
try { Thread.sleep(100); } catch (InterruptedException e) { }
}
static long ms(Runnable r) {
long t0 = System.nanoTime();
r.run();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
System.out.println("common pool parallelism = " + ForkJoinPool.commonPool().getParallelism()
+ " (+ the calling thread = 12 workers)");
long a = ms(() -> IntStream.range(0, 50).parallel().forEach(i -> callApi()));
System.out.println("50 blocking calls, parallelStream : " + a + " ms (50 / 12 -> 5 waves of 100 ms)");
long b = ms(() -> {
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 50).forEach(i -> ex.submit(BlockingPool::callApi));
} // close() waits for all 50
});
System.out.println("50 blocking calls, virtual threads : " + b + " ms");
// the damage to OTHER code: an unrelated task that needs the common pool
long idle = ms(() -> CompletableFuture.supplyAsync(() -> "ping").join());
System.out.println("unrelated supplyAsync, pool idle : " + idle + " ms");
Thread blocker = new Thread(() -> IntStream.range(0, 50).parallel().forEach(i -> callApi()));
blocker.start();
Thread.sleep(150); // let the blocking job occupy every worker
long busy = ms(() -> CompletableFuture.supplyAsync(() -> "ping").join());
System.out.println("unrelated supplyAsync, pool blocked : " + busy + " ms");
blocker.join();
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}common pool parallelism = 11 (+ the calling thread = 12 workers)
50 blocking calls, parallelStream : 504 ms (50 / 12 -> 5 waves of 100 ms)
50 blocking calls, virtual threads : 127 ms
unrelated supplyAsync, pool idle : 3 ms
unrelated supplyAsync, pool blocked : 150 ms
// measured on the course machine (12 cores); your numbers will differThe arithmetic matches the pool size. There are 12 workers (11 plus the caller) for 50 tasks of 100 ms each, so the tasks run in 50 / 12 = about 5 waves, and 5 × 100 ms is about 500 ms. The measured 504 ms agrees. A virtual-thread executor does not limit concurrent sleepers to the number of cores, so all 50 waited at the same time and finished in 127 ms, about four times faster.
The last two lines are the real damage. An unrelated one-line task takes 3 ms when the common pool is idle. While the blocking stream occupied all workers, the same task took 150 ms, which is the time until a worker became free. Every endpoint that touches the common pool got slower, including ones that do not call any REST service. This is the cause behind "an endpoint made another endpoint freeze".
Idiom: parallelise only when five conditions hold, and measure
The problem: .parallel() is one word, so it gets added as a "free speed-up". Sometimes it is a 5x win, sometimes a 100x loss, and sometimes it silently breaks the answer.
How it works: the speed-up is roughly the number of cores, minus the cost of splitting, merging and waiting. All five conditions in the checklist below must hold for the cost to be small compared to the gain. If one fails, stay sequential, or choose a different tool.
- Big N times costly per element: thousands of elements with real CPU work each (the primes example), or millions of cheap ones. A rough guide: the whole job is over a few milliseconds sequentially.
- A source that splits well: array,
ArrayList,IntStream.range. - No shared mutable state, and a merge that is associative:
collect,sum,reducewith a pure function. - No blocking: no network, database, file or
sleepcalls inside. For those, use a thread pool or virtual threads. - Measured: run sequential and parallel on realistic data, on the real hardware, several times. Keep
.parallel()only if the gain is clear.
- Works: primes over 2,000,000 numbers (5.4x on 12 cores), a big
ArrayListwith a few multiplications per element (about 7x), acollect(groupingBy(...))over millions of rows. - Fails: 10 elements (136x slower), a
LinkedListoriteratesource,forEachOrdered, sleeping or REST calls in the lambda (500 ms against 127 ms, and a 150 ms stall for others). - Interview takeaway: "A parallel stream helps for large, CPU-bound, independent work on a source that splits well, with no shared state and no blocking. I measure it. I never use it for I/O, because the common pool has only cores minus one threads and is shared by the whole JVM."
The custom pool workaround, and its catch
Sometimes you must run a parallel stream but you do not want it to use the common pool. A known trick is to start the stream from inside a task that runs in your own ForkJoinPool. A parallel stream started from a worker of a pool uses that pool.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class CustomPoolTrick {
public static void main(String[] args) throws Exception {
ForkJoinPool mine = new ForkJoinPool(4); // my own pool, 4 workers
Set<String> names = ConcurrentHashMap.newKeySet();
mine.submit(() -> // the stream is started FROM a worker of 'mine'
IntStream.range(0, 100).parallel().forEach(i -> {
names.add(Thread.currentThread().getName());
try { Thread.sleep(5); } catch (InterruptedException e) { }
})).get();
System.out.println("threads used: " + new TreeSet<>(names));
System.out.println("none of them is a ForkJoinPool.commonPool worker: "
+ names.stream().noneMatch(n -> n.contains("commonPool")));
mine.shutdown();
}
}threads used: [ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-2, ForkJoinPool-1-worker-3, ForkJoinPool-1-worker-4]
none of them is a ForkJoinPool.commonPool worker: trueAll the work ran on the four threads of ForkJoinPool-1, and none on the common pool. That isolates a heavy job from the rest of the application. But read the catch carefully: this behaviour is an implementation detail, not a promise in the documentation. A later JDK might change it without warning. You also own the pool now, so you must size it and call shutdown(). And it still does not make blocking calls fast: 4 threads sleeping is still only 4 at a time.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Sequential stream or loop | Under a few thousand cheap elements, or any work you did not measure. | Uses one core. That is usually fine. |
parallelStream() on the common pool | Big, CPU-bound, independent, splittable, non-blocking work. | Shared pool of cores minus 1. Wrong with shared state. Slower if small. |
Parallel stream in your own ForkJoinPool | A heavy CPU job that must not starve the common pool. | Relies on undocumented behaviour. You manage the pool. |
| Fixed thread pool of about cores (section 10) | CPU-bound tasks you want to submit and control (timeouts, cancel). | More code than a stream. You choose the pool size and shut it down. |
| Virtual threads (section 12) | Many tasks that mostly wait (network, database). | No speed-up for CPU work. Needs Java 21 or later. |
Gatherers.mapConcurrent (Java 24) | A slow call per element inside a stream, keeping order and a concurrency limit. | Needs Java 24. Limited to the mapping step. |
A fair summary of the section: parallel streams are a power tool for one narrow job. They are not a general way to make code faster. The threads, locks and executors that the next sections explain are the tools for everything else, and they are the reason for the warnings you just read. In Chapter E3 the interview side of the same topics is drilled in depth.
Before the next section, one idea to keep: a parallel stream is still your code running on several threads. Everything that goes wrong with threads can go wrong inside your lambda, which is why the next section starts from a single thread and builds up slowly.
08 · Threads from zeroThreads from Zero: Thread, Runnable, Callable, start and join
A thread is one independent line of execution inside your program. It has its own call stack, but it shares the heap (all the objects) with every other thread. start() creates a new line of execution, while run() is an ordinary method call on the current one. Threads that touch the same data without rules lose updates and miss each other's writes. This section builds each of those facts from a program you can run.
Back to QuickBite. When an order is delivered, the app sends the customer three notifications: a push message, an SMS and an email. Each call to a provider takes about 200 milliseconds. A developer wants the three to run "in parallel", so the customer hears about the delivery after 200 ms and not after 600.
The developer wraps each send in a Thread and calls run() on it. The code compiles, the notifications are all sent, and nothing looks wrong. But the job takes three times longer than expected, and in the logs every line names the same thread.
Make the invisible visible: the same three sends done two ways. Each send sleeps 200 ms and prints the name of the thread that ran it. The first loop calls run(), the second calls start() and then join().
import java.util.*;
public class StartVsRun {
static void notifyCustomer(String who) {
try { Thread.sleep(200); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.println(" sent to " + who + " on thread " + Thread.currentThread().getName());
}
public static void main(String[] args) throws Exception {
String[] customers = {"asha", "ravi", "meera"};
System.out.println("run() three times:");
long t0 = System.nanoTime();
for (String c : customers) {
new Thread(() -> notifyCustomer(c)).run(); // plain method call
}
System.out.println(" took " + (System.nanoTime() - t0) / 1_000_000 + " ms");
System.out.println("start() three times, then join():");
t0 = System.nanoTime();
List<Thread> threads = new ArrayList<>();
for (String c : customers) {
Thread t = new Thread(() -> notifyCustomer(c));
t.start(); // new call stack
threads.add(t);
}
for (Thread t : threads) t.join();
System.out.println(" took " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
}run() three times:
sent to asha on thread main
sent to ravi on thread main
sent to meera on thread main
took 604 ms
start() three times, then join():
sent to asha on thread Thread-3
sent to ravi on thread Thread-4
sent to meera on thread Thread-5
took 201 msWith run() the three sends happened one after the other on the thread named main, and the loop took 604 ms, which is 3 × 200 plus a little. With start() they ran on three new threads at the same time and the loop took 201 ms, which is one wait.
Look at the thread names in the second half: Thread-3, Thread-4, Thread-5. Why not Thread-0? Because Java gives a thread its default name when the Thread object is created, not when it starts. The first loop created three Thread objects (Thread-0 to Thread-2) and never started them. Each of them was only used as a place to call run().
That small detail is the whole bug in one picture. A Thread object is a handle for a thread. Calling a method on the handle is not the same as creating the thread it describes.
Idiom: start(), not run()
The problem: thread.run() compiles and works, so the mistake survives code review. It executes the task's body on the thread that called it. Nothing runs in parallel, and the caller is blocked until the body returns.
How it works: Thread.start() asks the JVM to create an operating-system thread with its own stack, and that new thread then calls run() for you. start() returns immediately. Calling start() a second time on the same object throws IllegalThreadStateException, because a thread can only be started once.
- Create:
new Thread(task)gives you a handle in state NEW. Nothing runs yet. - Start:
t.start()creates the real thread. The caller carries on at once. - Wait:
t.join()blocks the caller until the thread has finished. Skip it if you do not need to wait.
Without the idiom: each send runs on main, one after another.
for (String c : customers)
new Thread(() -> notifyCustomer(c)).run(); // plain call
sent to asha on thread main
sent to ravi on thread main
sent to meera on thread main
took 604 msWith the idiom: start every thread first, then join them all. The sends overlap.
for (String c : customers) {
Thread t = new Thread(() -> notifyCustomer(c));
t.start(); // new call stack
threads.add(t);
}
for (Thread t : threads) t.join();
sent to asha on thread Thread-3
sent to ravi on thread Thread-4
sent to meera on thread Thread-5
took 201 ms- Works:
start()for a new line of execution, andjoin()when the next step needs the result. Start all threads before joining any, otherwise you have written a slow sequential loop again. - Fails:
run()in place ofstart(). Alsostart(); join();inside the same loop iteration, which waits for each thread before creating the next. - Interview takeaway: "
run()is just a method.start()is what creates the thread. PrintThread.currentThread().getName()and you will see which one you did."
The deeper question is what "a new call stack" really means, and what the two threads share. The next picture answers it.
Bridge: what a thread is, one level down
A running Java program has one memory area for objects, called the heap. Every new allocates there. A thread does not own any of it.
What a thread does own is a call stack. The stack holds one entry (a frame) for every method that is currently running, with that method's local variables and its position in the code. When main calls notifyCustomer, a frame is pushed. When the method returns, the frame is popped. On this machine each stack can grow to 1,024 KB by default.
$ java -XX:+PrintFlagsFinal -version | grep ThreadStackSize
intx CompilerThreadStackSize = 1024 {pd product} {default}
intx ThreadStackSize = 1024 {pd product} {default}
intx VMThreadStackSize = 1024 {pd product} {default}So three threads means three stacks and still one heap. Local variables that hold numbers (int i) live in the stack and are private to the thread. Local variables that hold objects are only references: the reference sits in the stack, and the object it points to sits in the heap. Two threads can hold references to the same object.
Order mean three threads can read and change the same object, which is the source of every race in this chapter.This one picture explains why threads are useful and why they are dangerous. They are useful because sharing is cheap: no copying, any thread can read the order. They are dangerous for the same reason. If two threads change the same object at once, nothing in the language decides who goes first.
The operating system's scheduler decides which threads run on which CPU core at any moment. It can pause a thread at almost any instruction and give the core to another one, and you do not control when. With 12 cores, up to 12 threads can truly run at the same instant. With 5,000 threads, the scheduler switches between them very quickly. This is why a bug that appears once in a thousand runs is normal for threaded code.
Bridge: Thread, Runnable and Callable, one level down
There are three ways to describe "the work a thread should do". Two of them are old and one is newer. First, you can subclass Thread and override run(). That ties the work to the way it is run, and uses up your single inheritance slot. Avoid it.
Second, you can give the thread a Runnable: an interface with one method, void run(). It returns nothing and cannot throw a checked exception. A lambda is the shortest way to write one. The StartVsRun program above used it.
Third, a Callable<V> has one method, V call() throws Exception. It returns a value and may throw anything. The difference sounds small, but it is the difference between "do this" and "compute this for me and tell me if it failed".
Runnable
Does the work, returns nothing. A failure has nowhere to go but the thread's uncaught-exception handler.
Runnable r = () -> {
menu.reload(); // result? lost
};
new Thread(r).start();Callable
Returns a value and may throw. The caller gets either the value or the failure, through a Future.
Callable<Integer> c = () -> {
return menu.count(); // result kept
};
FutureTask<Integer> f =
new FutureTask<>(c);
new Thread(f).start();
int n = f.get();The shift: a Runnable is a fire-and-forget job; a Callable is a question whose answer, or failure, comes back to the asker.
A Thread only accepts a Runnable, so a Callable needs a small adapter. FutureTask is that adapter: it implements both Runnable (so a thread can run it) and Future (so you can ask for the result). In real code you rarely write this by hand, because an executor does the adapting for you. That is the topic of the next primer section. Here is the minimal version, run on the course machine, followed by what happens when the Callable fails.
import java.util.concurrent.*;
public class RunnableVsCallable {
static int menuCount() throws Exception { // checked exception allowed in Callable
Thread.sleep(300);
if (Boolean.getBoolean("fail")) throw new Exception("menu service is down");
return 42;
}
public static void main(String[] args) throws Exception {
// Runnable: no result, no checked exception
Runnable r = () -> System.out.println("runnable ran on " + Thread.currentThread().getName());
Thread t1 = new Thread(r, "worker-R");
t1.start(); t1.join();
// Callable: returns a value, may throw. A Thread cannot take one, so wrap it in a FutureTask.
Callable<Integer> c = RunnableVsCallable::menuCount;
FutureTask<Integer> task = new FutureTask<>(c);
new Thread(task, "worker-C").start();
System.out.println("menu items: " + task.get()); // blocks until done
}
}runnable ran on worker-R
menu items: 42$ java -Dfail=true RunnableVsCallable.java
runnable ran on worker-R
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.Exception: menu service is down
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:124)
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:193)
at RunnableVsCallable.main(RunnableVsCallable.java:20)
Caused by: java.lang.Exception: menu service is down
at RunnableVsCallable.menuCount(RunnableVsCallable.java:6)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:328)The checked exception from inside call() did not vanish and did not crash a background thread. Future.get() re-threw it, wrapped in an ExecutionException, and the original is under Caused by. A Runnable has no such path. If its body throws, the stack trace is printed by the thread's default handler and the program carries on.
Bridge: join, sleep, daemon threads and thread states, one level down
Four small facts about a thread's life come up in every interview and every production incident. Each one has a short program below.
Make the invisible visible: what join with a timeout does, and whether sleep lets go of a lock.
public class JoinSleepDemo {
static final Object lock = new Object();
public static void main(String[] args) throws Exception {
// 1. join with a timeout gives up waiting; it does not stop the other thread
Thread slow = new Thread(() -> {
try { Thread.sleep(500); } catch (InterruptedException e) { }
});
slow.start();
long t0 = System.nanoTime();
slow.join(100);
System.out.println("join(100) returned after " + (System.nanoTime() - t0) / 1_000_000
+ " ms, slow alive? " + slow.isAlive());
slow.join();
System.out.println("join() returned, slow alive? " + slow.isAlive());
// 2. sleep does NOT release a lock
Thread holder = new Thread(() -> {
synchronized (lock) {
System.out.println("holder: got lock, sleeping 500 ms");
try { Thread.sleep(500); } catch (InterruptedException e) { }
}
});
holder.start();
Thread.sleep(50);
long t1 = System.nanoTime();
synchronized (lock) {
System.out.println("main: got lock after " + (System.nanoTime() - t1) / 1_000_000 + " ms");
}
}
}join(100) returned after 100 ms, slow alive? true
join() returned, slow alive? false
holder: got lock, sleeping 500 ms
main: got lock after 450 msjoin(100) waited 100 ms and returned while the other thread was still alive. A timeout on join only limits how long you wait. It does not stop the other thread. After join() with no argument the thread was dead.
The second half is the one people get wrong. The holder thread took the lock and went to sleep for 500 ms. Main arrived 50 ms later and had to wait about 450 ms. sleep does not release any lock it holds. If you sleep inside a synchronized block, everyone who needs that lock waits for you. (Object.wait(), which you meet in the next section, does release it.)
Daemon and user threads
A JVM exits when the last user thread ends. A daemon thread is a background helper that does not count: when only daemons are left, the JVM stops and kills them mid-sentence. Thread pools for garbage collection and for timers are daemons. A thread you create is a user thread unless you call setDaemon(true) before start().
The program starts one background thread that sleeps three seconds, then lets main finish. It is run twice, with time around each run.
public class DaemonDemo {
public static void main(String[] args) {
boolean daemon = args.length > 0 && args[0].equals("daemon");
Thread t = new Thread(() -> {
try { Thread.sleep(3000); } catch (InterruptedException e) { }
System.out.println("background thread finished");
});
t.setDaemon(daemon);
t.start();
System.out.println("main finished (background thread daemon = " + daemon + ")");
}
}$ time java DaemonDemo
main finished (background thread daemon = false)
background thread finished
real 0m3.051s
$ time java DaemonDemo daemon
main finished (background thread daemon = true)
real 0m0.058sWith a user thread, main finished at once but the JVM stayed alive for 3.05 seconds, until the background thread was done. With a daemon thread, the JVM exited in 0.06 seconds and the "finished" line was never printed. The practical rule: if a thread holds something that must be completed (a file write, a payment), do not make it a daemon.
The six thread states
Java reports a thread's state through Thread.getState(). There are exactly six. The program below puts one thread through NEW, RUNNABLE, TIMED_WAITING and BLOCKED, and a second thread into WAITING, and prints each state as it happens.
public class ThreadStates {
static final Object lock = new Object();
public static void main(String[] args) throws Exception {
Thread t = new Thread(() -> {
long x = 0;
for (long i = 0; i < 400_000_000L; i++) x += i; // busy: RUNNABLE
try { Thread.sleep(300); } catch (InterruptedException e) { } // TIMED_WAITING
synchronized (lock) { } // BLOCKED while main holds it
System.out.println("worker sum " + x);
});
Thread w = new Thread(() -> { try { t.join(); } catch (InterruptedException e) { } });
System.out.println("before start: " + t.getState());
synchronized (lock) {
t.start();
Thread.sleep(50);
System.out.println("while computing: " + t.getState());
while (t.getState() != Thread.State.TIMED_WAITING) Thread.sleep(10);
System.out.println("inside sleep(300): " + t.getState());
while (t.getState() != Thread.State.BLOCKED) Thread.sleep(10);
System.out.println("wanting main's lock: " + t.getState());
w.start();
Thread.sleep(50);
System.out.println("a thread in join(): " + w.getState());
}
t.join();
w.join();
System.out.println("after finishing: " + t.getState());
}
}before start: NEW
while computing: RUNNABLE
inside sleep(300): TIMED_WAITING
wanting main's lock: BLOCKED
a thread in join(): WAITING
worker sum 79999999800000000
after finishing: TERMINATED| State | What it means | How a thread gets there |
|---|---|---|
NEW | Created, not started. | new Thread(...) before start(). |
RUNNABLE | Running, or ready to run and waiting for a core. | After start(); also while reading a socket (the OS is doing the waiting). |
BLOCKED | Waiting to enter a synchronized block. | Another thread holds that object's monitor. |
WAITING | Waiting with no time limit for another thread to act. | join(), Object.wait(), LockSupport.park(), an unbounded lock.lock() wait. |
TIMED_WAITING | Waiting with a time limit. | sleep(ms), join(ms), wait(ms), tryLock(time). |
TERMINATED | Finished. | run() returned or threw. |
A thread dump (jstack, shown in the next section) prints exactly these states. Learning to read them is the fastest way into a hung production system: many threads BLOCKED on one monitor means contention, many WAITING on one condition means a lost signal or an empty queue, and many RUNNABLE at 100% CPU means real computation or a spin loop.
The first race: count++ from four threads
Now the central problem. Four QuickBite request threads each count a delivered order 100,000 times into a shared counter. The right total is 400,000. A latch makes all four threads wait at a gate and then start together, so we see the worst case on purpose.
import java.util.concurrent.CountDownLatch;
public class RaceDemo {
static class Counter {
int count = 0;
void increment() { count++; }
}
public static void main(String[] args) throws Exception {
int threads = 4;
int perThread = args.length > 0 ? Integer.parseInt(args[0]) : 100_000;
for (int trial = 1; trial <= 5; trial++) {
Counter c = new Counter();
Thread[] ts = new Thread[threads];
CountDownLatch gate = new CountDownLatch(1); // all threads wait here, then go together
for (int i = 0; i < threads; i++) {
ts[i] = new Thread(() -> { try { gate.await(); } catch (InterruptedException e) { return; }
for (int k = 0; k < perThread; k++) c.increment(); });
ts[i].start();
}
gate.countDown();
for (Thread t : ts) t.join();
int expected = threads * perThread;
System.out.printf("run %d: expected %,d, got %,d, lost %,d%n",
trial, expected, c.count, expected - c.count);
}
}
}run 1: expected 400,000, got 164,932, lost 235,068
run 2: expected 400,000, got 279,221, lost 120,779
run 3: expected 400,000, got 302,221, lost 97,779
run 4: expected 400,000, got 400,000, lost 0
run 5: expected 400,000, got 400,000, lost 0Three of the five trials lost between 98,000 and 235,000 updates. Trials 4 and 5 got 400,000. Do not read that as "usually fine". Each trial is small enough that by the time the JVM has compiled the loop to fast machine code, a thread can finish its whole 100,000 increments before the next one wakes up, so the threads do not overlap. Starting a fresh JVM each time removes that effect.
fresh JVM 1: expected 400,000, got 189,740, lost 210,260
fresh JVM 2: expected 400,000, got 144,955, lost 255,045
fresh JVM 3: expected 400,000, got 162,567, lost 237,433
fresh JVM 4: expected 400,000, got 214,721, lost 185,279
fresh JVM 5: expected 400,000, got 176,860, lost 223,140Lost updates in 5 of 5 fresh launches: between 185,279 and 255,045 short of 400,000, which is half the work. A larger count shows the same thing: with 1,000,000 increments per thread (RaceDemo-1M.out in the code folder) trials 1 and 2 lost 1.13 million and 2.09 million updates.
An honest summary: this bug is intermittent. It depends on timing, on the number of cores, on whether the JIT compiler has run yet. It will pass your unit test and fail at 9 pm on Friday.
Why does it lose updates? count++ looks like one step, but it is three. The compiler's output shows it. We compile RaceDemo and print the bytecode of Counter.increment() with javap -c.
Compiled from "RaceDemo.java"
class RaceDemo$Counter {
int count;
RaceDemo$Counter();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_0
6: putfield #7 // Field count:I
9: return
void increment();
Code:
0: aload_0
1: dup
2: getfield #7 // Field count:I
5: iconst_1
6: iadd
7: putfield #7 // Field count:I
10: return
}The instructions at offsets 2 to 7 are the whole story. getfield reads count from the object on the heap. iconst_1 and iadd add one, on the thread's own operand stack. putfield writes the result back. Read, modify, write. Another thread can run between any two of those instructions.
That is a race condition in its smallest form. The result depends on how the steps of two threads happen to interleave. Four threads and 100,000 loops give this interleaving hundreds of thousands of chances to happen, which is why 185,000 to 255,000 updates disappeared. The fix is not "more careful code". It needs a rule that makes the three steps happen as one, and that is section 09.
Visibility: the worker that never stops
Lost updates need two threads writing. There is a second, stranger problem that needs only one writer. A QuickBite worker thread loops forever sending reminders, and the main thread should be able to tell it to stop by setting a boolean flag.
The code looks perfectly reasonable: the worker runs while (!stop) { ... }, and later main sets stop = true. The program below does exactly that, and gives the worker two seconds after the flag is set to notice. The worker is a daemon so the demo can exit; we also run it under timeout 5 in case it does not.
Make the invisible visible: a plain boolean flag, then the same code with the flag declared volatile.
public class VisibilityDemo {
static boolean stop = false; // try: static volatile boolean stop
static volatile boolean vstop = false;
public static void main(String[] args) throws Exception {
boolean useVolatile = args.length > 0 && args[0].equals("volatile");
long[] spins = new long[1];
Thread worker = new Thread(() -> {
long n = 0;
if (useVolatile) { while (!vstop) n++; }
else { while (!stop) n++; }
spins[0] = n;
System.out.println("worker saw the flag and stopped");
});
worker.setDaemon(true);
worker.start();
Thread.sleep(1000);
if (useVolatile) vstop = true; else stop = true;
System.out.println("main set the flag after 1 s");
worker.join(2000);
System.out.println("worker alive 2 s later? " + worker.isAlive());
}
}$ timeout 5 java VisibilityDemo.java
main set the flag after 1 s
worker alive 2 s later? true
(exit after 3.56 s)
exit code 0$ timeout 5 java VisibilityDemo.java volatile
main set the flag after 1 s
worker saw the flag and stopped
worker alive 2 s later? false
exit code 0With the plain flag, main set stop = true and, two seconds later, the worker was still running. I ran it four times with the default settings and the worker never stopped in any of them. With volatile the worker saw the change and ended at once.
Why does a write by one thread not reach another? There are two separate reasons, and either is enough. First, each CPU core keeps recently used memory in its own fast cache and registers, so a value written by core 1 may sit there for a while before core 2 sees it.
Second, and more important here, the JIT compiler is allowed to assume no other thread changes stop. A loop that reads a plain variable and never writes it can be compiled as "read once, then loop forever", because by the language rules the read can only give the same answer each time.
We can test the second reason. Running the same program with -Xint turns the JIT compiler off and interprets every instruction. The result:
$ timeout 5 java -Xint VisibilityDemo.java (interpreter only, no JIT compiler)
worker saw the flag and stopped
main set the flag after 1 s
worker alive 2 s later? falseWithout the JIT the worker stopped. So on this machine the hang is the JIT hoisting the read out of the loop. That is an optimisation the Java Memory Model permits, so the code is wrong on every JVM, even on one where this particular run happens to work. A different JDK, a different CPU or a different loop body can change the outcome without changing the verdict.
Idiom: a volatile stop flag
The problem: one thread writes a flag, another thread loops on it. Without a rule the reader may never see the new value, and the loop spins forever or for a long time.
How it works: a write to a volatile variable is guaranteed to be visible to every later read of that variable by any thread. The JIT compiler may not cache or hoist reads of it. It does not make compound actions such as count++ atomic, and it does not lock anything. It is only about visibility and ordering.
- One writer, simple flag: declare it
private volatile boolean running = true;. - Loop on it:
while (running) { ... }. - Stop it:
running = false;from any thread. The loop finishes its current round and exits. - If the loop blocks: a flag is not enough, because a thread stuck in
sleepor I/O will not look at it. Use interrupts (below).
static boolean stop = false;
...
while (!stop) n++; // JIT: read once, loop forever
worker alive 2 s later? truestatic volatile boolean vstop = false;
...
while (!vstop) n++; // every iteration re-reads
worker saw the flag and stopped
worker alive 2 s later? false- Works: a status flag with a single writer, a "ready" flag that publishes data written before it, a cached configuration value replaced as a whole object.
- Fails:
volatile int count; count++(still three steps, still races). Checking a flag and then acting on it as if nothing changed in between. A flag that a thread blocked insleepwill never read. - Interview takeaway: "
volatilegives visibility and ordering, not atomicity. It is right for a flag one thread sets and others read, and wrong forcount++."
Bridge: happens-before, in plain words
Java's rulebook for which writes a thread is guaranteed to see is the Java Memory Model. Its central idea is happens-before: if action A happens-before action B, then everything A wrote is visible to B. If there is no such chain between two actions, the JVM and the CPU may reorder or hide them, and you get the surprises above.
You do not need the formal definition. You need the short list of ways to create the chain, because those are the tools you are allowed to use.
- Thread start: everything a thread did before
t.start()is visible to the code insidet. That is why the worker could safely read variables main had set up. - Thread join: everything
tdid is visible to the caller aftert.join()returns. That is why the counters printed after the joins above were safe to read. - Volatile: a write to a volatile variable happens-before every later read of it.
- Locks: unlocking a monitor (leaving a
synchronizedblock) happens-before the next lock of the same monitor. This is the visibility half ofsynchronized, and the reason it fixes more than mutual exclusion. - Concurrent collections and executors: putting an object into a
BlockingQueue, or submitting a task, happens-before the other side takes it out or runs it.
If none of those connects two threads, assume nothing. The full model, including final fields and safe publication, is in E2's Java Memory Model section, and the interview questions on it are in E3.
Bridge: interrupts, one level down
A volatile flag stops a loop that is awake. Most real worker loops spend their time blocked: in sleep, in wait, in a queue's take(). For those, Java has a built-in cancel signal called an interrupt.
t.interrupt() does one of two things, depending on what t is doing. If t is blocked in sleep, wait, join or a similar call, that call stops waiting and throws InterruptedException. If t is running normally, the call only sets a boolean interrupted flag on the thread, and it is the code's job to look at it with Thread.currentThread().isInterrupted().
One detail catches people out. When sleep throws InterruptedException, it clears the flag first. The signal is now carried by the exception only. If you catch the exception and do nothing, the cancel request is lost, and the thread that asked for the stop will wait forever. The rule: either rethrow it, or restore the flag with Thread.currentThread().interrupt().
Make the invisible visible: a notification loop that sends one message per 100 ms. Main interrupts it after 350 ms, and then interrupts a second thread that never sleeps.
public class InterruptDemo {
public static void main(String[] args) throws Exception {
Thread worker = new Thread(() -> {
int done = 0;
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(100); // pretend: send one notification
done++;
}
System.out.println("loop saw the flag, sent " + done);
} catch (InterruptedException e) {
System.out.println("sleep threw; flag is now " + Thread.currentThread().isInterrupted()
+ ", sent " + done);
Thread.currentThread().interrupt(); // restore the flag for callers
System.out.println("flag restored: " + Thread.currentThread().isInterrupted());
}
}, "notifier");
worker.start();
Thread.sleep(350);
worker.interrupt();
worker.join();
// interrupt a thread that is busy (never sleeps): only the flag is set
Thread busy = new Thread(() -> {
long n = 0;
while (!Thread.currentThread().isInterrupted()) n++;
System.out.println("busy loop exits because the flag is true");
});
busy.start();
Thread.sleep(100);
busy.interrupt();
busy.join();
}
}sleep threw; flag is now false, sent 3
flag restored: true
busy loop exits because the flag is trueThe first thread sent three messages and was then interrupted inside sleep. The exception arrived, and the flag read false because sleep cleared it. The thread printed that and then put the flag back, so code further up the call chain can still see that a stop was requested. The second thread never sleeps, so no exception could be thrown at it. It only exits because its loop checks the flag.
So the rules for writing a cancellable task are short:
- Check the flag in loops that do not block:
while (!Thread.currentThread().isInterrupted()). - Let
InterruptedExceptiontravel out of your method (declarethrows) when you can. It is a cancel request, not an error. - If you must catch it, restore the flag with
Thread.currentThread().interrupt()and return. Never leave an emptycatchblock. - Interrupt does not kill. A thread that ignores the signal keeps running. Java deliberately has no safe "force stop" (
Thread.stop()was removed because it could leave objects half-updated).
Executors use this same mechanism. Future.cancel(true) and ExecutorService.shutdownNow() both work by interrupting worker threads, which is why a task that swallows InterruptedException makes a service impossible to stop cleanly. You will see it again in the executors section.
That completes the toolbox for single threads: create them with start(), wait with join(), make a stop flag volatile, and cancel blocked ones with interrupts. What is still missing is a way to make several steps happen as one, and that is the subject of the next section. E3 has a long set of interview questions on everything above, starting at its threads chapter.
09 · SynchronizationSynchronization: synchronized, volatile, Atomics and Locks
Synchronization means making several steps behave as one, so no other thread sees them half done. Java gives you four tools: synchronized (a built-in lock on any object), atomic classes (lock-free single variables), explicit locks such as ReentrantLock, and volatile (visibility only). This section builds each from a bug, shows what it costs, and ends with a table for choosing.
QuickBite has customer wallets: prepaid balances used to pay for orders. A debit method looks harmless: if (balance >= amt) balance -= amt;. The check is there so a wallet can never go below zero.
One evening two of a customer's orders were charged at the same instant, from two request threads. The balance was ₹10, each debit was ₹7, and both threads passed the check (10 is at least 7) before either subtracted. The wallet ended at -₹4. Support found a few hundred negative wallets that week.
The check and the subtraction are two steps. A thread can be paused between them, and the answer it got from the check is then stale. This is called check-then-act.
Make the invisible visible: 200 fresh ₹1,000 wallets. For each one, 8 threads start together and each makes 1,000 debits of ₹7. Run it once with the plain method and once with a synchronized method. The fraudCheck() call stands in for a quick rules lookup between the check and the update.
import java.util.concurrent.CountDownLatch;
public class WalletRace {
static void fraudCheck() { // stands in for a quick rules lookup
for (int i = 0; i < 20; i++) Thread.onSpinWait();
}
static class Wallet {
int balance = 1000; // rupees
void debit(int amt) { // plain version
if (balance >= amt) { fraudCheck(); balance -= amt; }
}
synchronized void debitSafe(int amt) { // fixed version
if (balance >= amt) { fraudCheck(); balance -= amt; }
}
}
static int run(boolean safe) throws Exception {
Wallet w = new Wallet();
CountDownLatch gate = new CountDownLatch(1);
Thread[] ts = new Thread[8];
for (int i = 0; i < ts.length; i++) {
ts[i] = new Thread(() -> {
try { gate.await(); } catch (InterruptedException e) { return; }
for (int k = 0; k < 1000; k++) { // 1,000 debits of Rs 7
if (safe) w.debitSafe(7); else w.debit(7);
}
});
ts[i].start();
}
gate.countDown();
for (Thread t : ts) t.join();
return w.balance;
}
public static void main(String[] args) throws Exception {
for (boolean safe : new boolean[] {false, true}) {
int negative = 0, worst = 0;
for (int trial = 1; trial <= 200; trial++) { // 200 fresh wallets of Rs 1,000
int b = run(safe);
if (b < 0) negative++;
worst = Math.min(worst, b);
}
System.out.println((safe ? "synchronized debit: " : "plain debit: ")
+ "negative in " + negative + " of 200 wallets, worst balance Rs " + worst);
}
}
}plain debit: negative in 199 of 200 wallets, worst balance Rs -36
synchronized debit: negative in 0 of 200 wallets, worst balance Rs 0The plain version went negative in 199 of 200 wallets, as low as ₹-36 (several threads all passed the check on a tiny balance and then each subtracted ₹7). The synchronized version never went below zero, in all 200.
One honest note. When I first ran the program without the fraudCheck() call, the plain version went negative in only 1 of 200 wallets and 0 of 200 on later runs. The window between the check and the update was a few nanoseconds wide. A real debit has a database or a rules lookup in that window, which makes the bug common. A bug that is rare in a test is not a bug that is rare in production.
Now the fix itself. Understanding why synchronized works means looking at what it actually does to an object.
Bridge: synchronized, one level down
Every Java object has a hidden monitor: a lock with a waiting room. A monitor has three parts. The owner is the one thread currently inside. The entry set holds threads that want in and are blocked until the owner leaves. The wait set holds threads that went in, called wait() and gave the monitor up on purpose to sleep until someone calls notify().
wait() sleep in the wait set until a notify().The keyword has three forms. We compile a class with a synchronized method and a synchronized block, and read the bytecode with javap.
public class MonitorBytecode {
int n;
synchronized void viaMethod() { n++; }
void viaBlock() { synchronized (this) { n++; } }
}$ javap -v -p MonitorBytecode | grep -A2 "synchronized void"
synchronized void viaMethod();
descriptor: ()V
flags: (0x0020) ACC_SYNCHRONIZED
$ javap -c -p MonitorBytecode (viaBlock only)
void viaBlock();
Code:
0: aload_0
1: dup
2: astore_1
3: monitorenter
4: aload_0
5: dup
6: getfield #7 // Field n:I
9: iconst_1
10: iadd
11: putfield #7 // Field n:I
14: aload_1
15: monitorexit
16: goto 24
19: astore_2
20: aload_1
21: monitorexit
22: aload_2
23: athrow
24: return
Exception table:
from to target type
4 16 19 any
19 22 19 anyA synchronized method has no special instructions. The compiler only sets a flag, ACC_SYNCHRONIZED, on the method, and the JVM takes and releases the lock around the call. A synchronized block compiles to monitorenter and monitorexit. Notice that monitorexit appears twice: once on the normal path (offset 15) and once on the exception path (offset 21). The compiler adds a hidden try/finally for you. That is why the lock is released even if the body throws, and why you do not need to write unlock yourself.
Which object is locked?
The lock belongs to an object, so the real question is always "which object?". There are three cases.
- Instance method: locks
this. Two threads calling it on the same object take turns. On different objects they do not block each other. - Static method: locks the class object (
Kitchen.class). One lock for all instances. - Block: locks whatever object you name in the brackets. A private
final Object lockfield is the safest choice, because no outside code can lock it by mistake.
The program below proves each one with timing. Every method sleeps 300 ms inside its lock, and two threads call them at the same time. Same lock gives about 600 ms (they queue). Different locks give about 300 ms (they overlap).
public class LockTargets {
static class Kitchen {
synchronized void cook() { pause(); } // locks 'this'
static synchronized void sweep() { pause(); } // locks Kitchen.class
void plate() { synchronized (this) { pause(); } } // same as cook()
}
static void pause() { try { Thread.sleep(300); } catch (InterruptedException e) { } }
static long both(Runnable a, Runnable b) throws Exception {
Thread x = new Thread(a), y = new Thread(b);
long t0 = System.nanoTime();
x.start(); y.start(); x.join(); y.join();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
Kitchen k1 = new Kitchen(), k2 = new Kitchen();
System.out.println("cook() on the SAME object, 2 threads: " + both(k1::cook, k1::cook) + " ms");
System.out.println("cook() on TWO objects, 2 threads: " + both(k1::cook, k2::cook) + " ms");
System.out.println("cook() and plate() on the same object: " + both(k1::cook, k1::plate) + " ms");
System.out.println("static sweep() twice (one lock per class): " + both(Kitchen::sweep, Kitchen::sweep) + " ms");
System.out.println("static sweep() and cook() (different locks): " + both(Kitchen::sweep, k1::cook) + " ms");
}
}cook() on the SAME object, 2 threads: 601 ms
cook() on TWO objects, 2 threads: 300 ms
cook() and plate() on the same object: 600 ms
static sweep() twice (one lock per class): 600 ms
static sweep() and cook() (different locks): 300 msLine 1 and 3: cook() and plate() both lock this, so they queue (601 and 600 ms). Line 2: two different Kitchen objects have two different locks, so 300 ms. Line 4: a static method locks the class, so two calls queue (600 ms). Line 5: the class lock and an instance lock are different locks, so a static method and an instance method do not exclude each other (300 ms). Synchronizing on the wrong object is a very common bug: the code looks protected and is not.
Mutual exclusion and visibility
synchronized gives you two guarantees at once. Mutual exclusion: only one thread at a time runs code guarded by the same monitor. Visibility: when a thread leaves the block, everything it wrote is published, and the next thread that enters the same monitor sees all of it. The second guarantee is why you do not also need volatile on a field you only touch inside synchronized code.
Both guarantees only hold if every access uses the same lock. A field that is written inside synchronized but read outside it has no happens-before chain. The reader can see old data. Reads need the lock too.
Reentrancy
What if a synchronized method calls another synchronized method on the same object? A non-reentrant lock would make the thread wait for itself and hang. Java monitors are reentrant: the owner can enter again, and the monitor counts how many times it entered and releases only when that count returns to zero. This is also what lets a subclass call super.method() when both are synchronized.
Idiom: guard shared state with one lock
The problem: several threads read and change the same fields. Without a lock, updates are lost (the count++ race) or invariants break (the wallet below zero).
How it works: pick one lock object for each group of fields that must change together. Every read and write of those fields happens inside synchronized on that lock. Keep the guarded section short and never call unknown code (callbacks, I/O) inside it.
- Find the invariant: what must be true between steps? (balance >= 0, size equals the number of items.)
- Choose the lock:
synchronizedmethods for a small class, or a privatefinal Object lockfor more control. - Guard every access: reads as well as writes.
- Keep it short: no sleeping or network calls inside the block.
The earlier race, fixed. Same four threads, same 100,000 increments each, same counter. This time next to each plain total is the synchronized one, with timings. At the end, the reentrancy check.
import java.util.concurrent.CountDownLatch;
public class SyncCounter {
static class Plain { int n; void inc() { n++; } }
static class Safe { int n; synchronized void inc() { n++; } }
// runs inc() per times on each of 'threads' threads at once; returns elapsed ms
static long hammer(Runnable inc, int threads, int per) throws Exception {
CountDownLatch gate = new CountDownLatch(1);
Thread[] ts = new Thread[threads];
for (int i = 0; i < threads; i++) {
ts[i] = new Thread(() -> {
try { gate.await(); } catch (InterruptedException e) { return; }
for (int k = 0; k < per; k++) inc.run();
});
ts[i].start();
}
long t0 = System.nanoTime();
gate.countDown();
for (Thread t : ts) t.join();
return (System.nanoTime() - t0) / 1_000_000;
}
// reentrancy: a synchronized method calls another one on the same object
static class Outer {
synchronized void a() { System.out.println("a: got the monitor"); b(); }
synchronized void b() { System.out.println("b: same thread, same monitor, no deadlock"); }
}
public static void main(String[] args) throws Exception {
int threads = 4, per = 100_000;
System.out.println("expected total: " + threads * per);
for (int run = 1; run <= 5; run++) {
Plain p = new Plain();
long a = hammer(p::inc, threads, per);
Safe s = new Safe();
long b = hammer(s::inc, threads, per);
System.out.printf("run %d: plain %,d (%d ms) | synchronized %,d (%d ms)%n",
run, p.n, a, s.n, b);
}
new Outer().a();
}
}expected total: 400000
run 1: plain 310,706 (21 ms) | synchronized 400,000 (41 ms)
run 2: plain 399,016 (0 ms) | synchronized 400,000 (36 ms)
run 3: plain 206,122 (2 ms) | synchronized 400,000 (25 ms)
run 4: plain 400,000 (0 ms) | synchronized 400,000 (43 ms)
run 5: plain 400,000 (0 ms) | synchronized 400,000 (32 ms)
a: got the monitor
b: same thread, same monitor, no deadlockThe unsynchronized total is wrong in the first three rounds (310,706, 399,016, 206,122) and happens to be right in rounds 4 and 5, for the same timing reason as before. The synchronized total is 400,000 in all five rounds. The price is time: 25 to 43 ms against 0 to 21 ms.
Part of that is real lock cost, part is that the unsynchronized loop was finishing before the other threads had started, so it measures less work than it appears to. Do not read it as "synchronization costs 40×". The honest number comes from the benchmark in the next part, with all eight threads fighting over the same variable.
The last two lines show reentrancy: a() holds the monitor and calls b(), which needs the same monitor, and nothing hangs.
- Works: a small critical section guarded by one lock that every access uses. Private lock objects. Immutable data (nothing to guard).
- Fails: locking on different objects for different threads. Synchronizing a writer but not the reader. Locking on a
Stringliteral, a boxedIntegeror a public field (other code can share your lock by accident). Holding the lock across a network call. - Interview takeaway: "
synchronizedgives mutual exclusion and visibility on one monitor. Every access to the data must use the same lock, and the guarded section should be short."
Bridge: volatile, synchronized or an atomic, one level down
Three tools fix three different problems, and mixing them up is the most common concurrency mistake in code reviews. Before the details, here is the question to ask: what is the operation?
| Operation | Example | Right tool | Why the others fail |
|---|---|---|---|
| One thread writes, others read a single variable | running = false | volatile | Cheapest. No lock needed, because nothing is read and then written. |
| Read, change and write one variable | count++, max = Math.max(max, x) | AtomicInteger / AtomicLong (or LongAdder for counters) | volatile still loses updates because it does not join the three steps. |
| Change two or more variables together | debit one wallet, credit another | synchronized or a Lock | Atomics are one variable at a time. Two atomics can be in an inconsistent state between the calls. |
| Check, then act on the result | if (!list.contains(x)) list.add(x) | A lock around both steps, or a single atomic method such as putIfAbsent | Each step may be thread-safe alone, but the pair is not. |
Compare-and-set, in plain words
An atomic class does not use a lock. It uses one special CPU instruction, compare-and-set (CAS): "write this new value, but only if the variable still holds the value I read earlier; tell me whether it worked". The CPU does the compare and the write as one indivisible step. The classic way to use it is a loop: read, compute, try to write, and if someone else changed the value in between, go back and read again.
That loop is what incrementAndGet() does inside. Here it is written by hand, with a counter of how many times a thread lost the race and had to retry.
import java.util.concurrent.atomic.AtomicInteger;
public class CasLoop {
static final AtomicInteger value = new AtomicInteger(41);
static final AtomicInteger retries = new AtomicInteger();
// what incrementAndGet() does, written by hand
static int myIncrement() {
while (true) {
int seen = value.get(); // 1. read the current value
int next = seen + 1; // 2. compute the new one
if (value.compareAndSet(seen, next)) // 3. write only if still 'seen'
return next;
retries.incrementAndGet(); // someone else got in first: go again
}
}
public static void main(String[] args) throws Exception {
System.out.println("compareAndSet(41, 42): " + new AtomicInteger(41).compareAndSet(41, 42));
System.out.println("compareAndSet(40, 99): " + new AtomicInteger(41).compareAndSet(40, 99) + " (value was 41, not 40)");
Thread[] ts = new Thread[4];
for (int i = 0; i < ts.length; i++) {
ts[i] = new Thread(() -> { for (int k = 0; k < 250_000; k++) myIncrement(); });
ts[i].start();
}
for (Thread t : ts) t.join();
System.out.println("value: " + value.get() + " (expected " + (41 + 4 * 250_000) + ")");
System.out.println("retries (lost the race, tried again): " + retries.get());
}
}compareAndSet(41, 42): true
compareAndSet(40, 99): false (value was 41, not 40)
value: 1000041 (expected 1000041)
retries (lost the race, tried again): 452532The first two lines show the contract: compareAndSet(41, 42) works, and compareAndSet(40, 99) fails because the value was 41 and not 40. After four threads made 250,000 increments each, the total is exactly right (1,000,041 = 41 + 1,000,000). The last line is the cost of the optimistic method: 452,532 retries. Roughly one attempt in three lost the race and had to run again. Nothing was blocked, no thread was put to sleep, but under heavy contention a lot of work is repeated.
That is the key trade. A lock makes losers wait. CAS makes losers retry. With light contention retrying is far cheaper than parking a thread. With very heavy contention on one variable, the retries themselves become the bottleneck, and that is the problem LongAdder was added to solve in Java 8.
Bridge: AtomicLong and LongAdder under contention
LongAdder keeps not one counter but an array of cells. Each thread tends to update its own cell, so threads do not fight over one memory location. sum() adds the cells up when you ask. It is built for the case "many threads increment, someone reads the total now and then" (a request counter, a metric). The price: sum() is not an exact snapshot while updates are happening, and it cannot do compare-and-set.
The benchmark: 8 threads, each doing 5,000,000 increments on one shared number, which makes 40,000,000 in total. It is done three ways: a synchronized block, an AtomicLong, and a LongAdder. Run in three separate JVM launches, three rounds each, because the results moved around.
import java.util.concurrent.atomic.*;
public class AtomicBench {
static long counter = 0;
static final Object LOCK = new Object();
static final AtomicLong atomic = new AtomicLong();
static final LongAdder adder = new LongAdder();
static long run(Runnable body, int threads) throws Exception {
Thread[] ts = new Thread[threads];
for (int i = 0; i < threads; i++) ts[i] = new Thread(body);
long t0 = System.nanoTime();
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
int threads = 8, per = 5_000_000;
for (int round = 1; round <= 3; round++) {
counter = 0; atomic.set(0); adder.reset();
long a = run(() -> { for (int i = 0; i < per; i++) synchronized (LOCK) { counter++; } }, threads);
long b = run(() -> { for (int i = 0; i < per; i++) atomic.incrementAndGet(); }, threads);
long c = run(() -> { for (int i = 0; i < per; i++) adder.increment(); }, threads);
System.out.printf("round %d: synchronized %5d ms | AtomicLong %5d ms | LongAdder %5d ms%n", round, a, b, c);
if (round == 3)
System.out.println("totals: " + counter + " " + atomic.get() + " " + adder.sum()
+ " (expected " + (long) threads * per + ")");
}
}
}# JVM launch 1
round 1: synchronized 2727 ms | AtomicLong 384 ms | LongAdder 49 ms
round 2: synchronized 2201 ms | AtomicLong 353 ms | LongAdder 45 ms
round 3: synchronized 675 ms | AtomicLong 369 ms | LongAdder 32 ms
totals: 40000000 40000000 40000000 (expected 40000000)
# JVM launch 2
round 1: synchronized 2625 ms | AtomicLong 379 ms | LongAdder 55 ms
round 2: synchronized 2574 ms | AtomicLong 390 ms | LongAdder 49 ms
round 3: synchronized 246 ms | AtomicLong 380 ms | LongAdder 50 ms
totals: 40000000 40000000 40000000 (expected 40000000)
# JVM launch 3
round 1: synchronized 1088 ms | AtomicLong 388 ms | LongAdder 58 ms
round 2: synchronized 629 ms | AtomicLong 389 ms | LongAdder 36 ms
round 3: synchronized 2010 ms | AtomicLong 401 ms | LongAdder 24 ms
totals: 40000000 40000000 40000000 (expected 40000000)All three always reached the right total, 40,000,000. The timings tell a story with a wobble in it.
LongAdder: 24 to 58 ms in all nine rounds. Stable and by far the fastest.AtomicLong: 353 to 401 ms in all nine rounds. Very stable, roughly 7 to 17 times slower than the adder, because every thread competes for the same cache line and many CAS attempts fail.synchronized: anywhere from 246 ms to 2,727 ms. Eight of the nine rounds took over 600 ms, and three took over 2.5 seconds. One round (246 ms) was even faster thanAtomicLong, probably because the lock stayed with one thread for a long uninterrupted run.
The honest reading is not "synchronized is 10× slower". It is that a contended lock has unpredictable cost. Threads that cannot get the monitor are parked and woken by the operating system, which takes microseconds each time, and whether a run is lucky depends on scheduling.
The atomic's cost is steady, and the adder's is smallest. If a counter is hot (thousands of increments per millisecond from many cores), use LongAdder. If it is touched a few thousand times a second, any of the three is fine and the simplest one wins.
Idiom: atomic counters instead of locks
The problem: a counter or a running maximum is shared by many threads. A synchronized method works but has unpredictable cost under contention. A plain volatile counter is simply wrong.
How it works: an atomic class applies one operation (incrementAndGet, addAndGet, updateAndGet, accumulateAndGet, compareAndSet) as a single indivisible step with a CPU compare-and-set. LongAdder and LongAccumulator spread the contention over several cells for write-heavy counters.
- One variable, simple update: use
AtomicInteger,AtomicLongorAtomicReference. - Hot counter, read rarely: use
LongAdderand callsum()to read. - Update depends on the old value:
updateAndGet(x -> ...)or your owncompareAndSetloop. The function must have no side effects, because it may run more than once. - Two variables must agree: atomics are not enough. Use a lock.
synchronized (LOCK) { counter++; }
// 8 threads x 5,000,000: 246 ms ... 2,727 msatomic.incrementAndGet(); // 353 ... 401 ms
adder.increment(); // 24 ... 58 ms- Works: counters, sequence numbers (
AtomicLong.incrementAndGet()), a "highest value seen" withaccumulateAndGet(x, Math::max),LongAdderfor metrics,AtomicReferenceto swap in a new immutable config object. - Fails: using two atomics as if they were one transaction (
balance.addAndGet(-x); log.incrementAndGet();can be observed half done). An update function with side effects (it may be retried).LongAdder.sum()used for exact decisions such as "stop at exactly 1,000". - Interview takeaway: "An atomic turns read-modify-write on one variable into one CPU step. For a very hot counter,
LongAdderspreads the contention and is far faster. For two variables that must agree, use a lock."
Bridge: check-then-act with thread-safe collections
The wallet bug was a check followed by an action on a plain field. The same bug appears when every single call is already thread-safe. Collections.synchronizedList wraps a list so that every method takes a lock. That makes contains safe and add safe. It does not make the pair safe, because the lock is released between the two calls.
The program below puts 1,000 rider ids into a synchronized list from 8 threads, each of which tries every id. The rule is "add only if not already present", so the final size must be 1,000. The second half does the same but holds one lock around both steps.
import java.util.*;
import java.util.concurrent.CountDownLatch;
public class CheckThenAct {
public static void main(String[] args) throws Exception {
for (boolean fixed : new boolean[] {false, true})
for (int trial = 1; trial <= 5; trial++) {
List<String> riders = Collections.synchronizedList(new ArrayList<>());
CountDownLatch gate = new CountDownLatch(1);
Thread[] ts = new Thread[8];
for (int i = 0; i < ts.length; i++) {
ts[i] = new Thread(() -> {
try { gate.await(); } catch (InterruptedException e) { return; }
for (int k = 0; k < 1000; k++) {
String id = "rider-" + k;
if (fixed) {
synchronized (riders) { // one lock around check AND act
if (!riders.contains(id)) riders.add(id);
}
} else if (!riders.contains(id)) { // check: safe on its own
riders.add(id); // act: another thread may have added it
}
}
});
ts[i].start();
}
gate.countDown();
for (Thread t : ts) t.join();
System.out.println((fixed ? "one lock " : "check, act ") + "run " + trial + ": 1000 distinct ids expected, list size " + riders.size()
+ ", duplicates " + (riders.size() - new HashSet<>(riders).size()));
}
}
}check, act run 1: 1000 distinct ids expected, list size 1039, duplicates 39
check, act run 2: 1000 distinct ids expected, list size 1469, duplicates 469
check, act run 3: 1000 distinct ids expected, list size 1313, duplicates 313
check, act run 4: 1000 distinct ids expected, list size 1126, duplicates 126
check, act run 5: 1000 distinct ids expected, list size 1118, duplicates 118
one lock run 1: 1000 distinct ids expected, list size 1000, duplicates 0
one lock run 2: 1000 distinct ids expected, list size 1000, duplicates 0
one lock run 3: 1000 distinct ids expected, list size 1000, duplicates 0
one lock run 4: 1000 distinct ids expected, list size 1000, duplicates 0
one lock run 5: 1000 distinct ids expected, list size 1000, duplicates 0With a thread-safe list but a separate check and add, every run had duplicates: 39 to 469 extra entries. With one synchronized block around both, there were none, in five of five runs. The lesson is a rule worth saying out loud in a design review: thread-safe parts do not compose into a thread-safe whole. The invariant ("no duplicates") spans two calls, so the lock has to span both.
For maps there is a ready-made single call: ConcurrentHashMap.putIfAbsent and computeIfAbsent do check-and-insert as one atomic step. They are shown in the executors section, with the duplicate-computation bug they fix.
Deadlock: two threads, two locks, no way out
Locks solve races and create a new problem. QuickBite lets a customer move wallet money between accounts: transfer(from, to, amount). To make it atomic, the method locks the source account, then the destination account, then moves the money. Both accounts' balances change together, so both need protection.
At lunch, thread 1 runs transfer(A, B) while thread 2 runs transfer(B, A). Thread 1 locks A and thread 2 locks B. Now thread 1 wants B, which thread 2 holds, and thread 2 wants A, which thread 1 holds. Neither can move. Neither will ever let go. The two request threads are gone from the pool forever, and each time it happens another two follow.
This is a deadlock. It needs all four of these conditions at once: threads hold a lock while waiting for another, locks cannot be taken away, only one thread can hold a lock at a time, and the waiting forms a circle. Break any one of them and it cannot happen.
Make the invisible visible: the program that deadlocks on purpose. A 100 ms pause between the two locks makes the interleaving reliable, so the demo does not depend on luck. It is run under timeout 5, and while it hangs we take a thread dump from another terminal with jstack.
public class Deadlock {
static class Account {
final int id; int balance;
Account(int id, int balance) { this.id = id; this.balance = balance; }
}
static void transfer(Account from, Account to, int amt) {
synchronized (from) { // lock the source first
pause(); // widen the window so the demo is reliable
synchronized (to) { // then the destination
from.balance -= amt;
to.balance += amt;
}
}
}
static void pause() { try { Thread.sleep(100); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
Account a = new Account(1, 5000), b = new Account(2, 5000);
Thread t1 = new Thread(() -> transfer(a, b, 100), "transfer-A-to-B");
Thread t2 = new Thread(() -> transfer(b, a, 200), "transfer-B-to-A");
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("done: a=" + a.balance + " b=" + b.balance);
}
}exit code 124 (124 = killed by timeout)The program printed nothing and was killed by timeout after five seconds (exit code 124). While it was hung, we ran jps to find its process id and then jstack <pid>. The JVM can detect the cycle itself, and the report is the first thing to look for in a dump from a frozen service.
Found one Java-level deadlock:
=============================
"transfer-A-to-B":
waiting to lock monitor 0x000074b830001c90 (object 0x00000000943182d8, a Deadlock$Account),
which is held by "transfer-B-to-A"
"transfer-B-to-A":
waiting to lock monitor 0x000074b824000f20 (object 0x00000000943182c0, a Deadlock$Account),
which is held by "transfer-A-to-B"
Java stack information for the threads listed above:
===================================================
"transfer-A-to-B":
at Deadlock.transfer(Deadlock.java:11)
- waiting to lock <0x00000000943182d8> (a Deadlock$Account)
- locked <0x00000000943182c0> (a Deadlock$Account)
at Deadlock.lambda$main$0(Deadlock.java:20)
at Deadlock$$Lambda/0x0000000036040420.run(Unknown Source)
at java.lang.Thread.runWith(java.base@25.0.5.1/Thread.java:1487)
at java.lang.Thread.run(java.base@25.0.5.1/Thread.java:1474)
"transfer-B-to-A":
at Deadlock.transfer(Deadlock.java:11)
- waiting to lock <0x00000000943182c0> (a Deadlock$Account)
- locked <0x00000000943182d8> (a Deadlock$Account)
at Deadlock.lambda$main$1(Deadlock.java:21)
at Deadlock$$Lambda/0x0000000036040c00.run(Unknown Source)
at java.lang.Thread.runWith(java.base@25.0.5.1/Thread.java:1487)
at java.lang.Thread.run(java.base@25.0.5.1/Thread.java:1474)
Found 1 deadlock.Read it from the top. transfer-A-to-B is "waiting to lock" the account object ending ...2d8, which is "held by" transfer-B-to-A. And transfer-B-to-A is waiting for ...2c0, held by transfer-A-to-B. The two lines "waiting to lock ... which is held by" make a circle.
Below it the stack traces show where each one is stuck: line 11 of Deadlock.java, the first statement inside the inner synchronized (to) block (the thread is stuck trying to enter it), with one locked line (the lock it owns) and one waiting to lock line (the lock it needs). The last line, Found 1 deadlock., is the summary.
How to find a deadlock in a running JVM, in order of effort: jstack <pid> (or jcmd <pid> Thread.print) prints the report above when the deadlock is made of monitors or java.util.concurrent locks. A JMX call to ThreadMXBean.findDeadlockedThreads() returns the same cycle from inside the program, which monitoring agents use. A tool such as VisualVM shows it graphically. For deadlocks that are not pure locks (a thread waiting for a queue that nobody fills) the JVM does not report it, and you read the stack traces yourself.
Idiom: take locks in a fixed global order
The problem: code needs two locks at once, and different callers can ask for them in different orders. The order depends on the arguments (transfer(A, B) versus transfer(B, A)), so the bug is invisible in single-threaded tests.
How it works: give the locks a total order, such as the account id, and always lock the lower one first no matter which is the source. A cycle needs one thread to hold a high lock while waiting for a low one, and the rule makes that impossible.
- Pick a stable key: a unique id that never changes (an account id, a database primary key).
- Sort: compare the two ids and call the lower
first, the othersecond. - Lock both in that order:
synchronized (first) { synchronized (second) { ... } }. Then move the money using the originalfromandto. - Ties and self-transfers: if the ids can be equal (the same account), lock once, or add a tie-breaker lock first.
synchronized (from) { // transfer(A,B) locks A first
synchronized (to) { ... } // transfer(B,A) locks B first
}
(no output: hung, killed by timeout 5, jstack: Found 1 deadlock)public class DeadlockFixed {
static class Account {
final int id; int balance;
Account(int id, int balance) { this.id = id; this.balance = balance; }
}
static void transfer(Account from, Account to, int amt) {
Account first = from.id < to.id ? from : to; // always lock the lower id first
Account second = from.id < to.id ? to : from;
synchronized (first) {
pause();
synchronized (second) {
from.balance -= amt;
to.balance += amt;
}
}
}
static void pause() { try { Thread.sleep(100); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
Account a = new Account(1, 5000), b = new Account(2, 5000);
Thread t1 = new Thread(() -> transfer(a, b, 100), "transfer-A-to-B");
Thread t2 = new Thread(() -> transfer(b, a, 200), "transfer-B-to-A");
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("done: a=" + a.balance + " b=" + b.balance);
}
}done: a=5100 b=4900The two transfers ran at the same time and finished. Account A started at 5,000 and sent 100 to B and received 200 back: 5,000 - 100 + 200 = 5,100. B ended at 4,900. Both threads locked account 1 before account 2, so the second thread simply waited its turn at the first lock.
- Works: locking by a fixed key order (id, memory address, name). Holding only one lock at a time when you can. Doing the work on a snapshot and taking the locks only for the final update.
- Fails: an order that is "usually" the same. Calling an overridable method or a callback while holding a lock (it may take another lock in a different order). Hidden second locks, such as a logger or a library call that synchronizes inside.
- Interview takeaway: "A deadlock is a cycle of threads each holding one lock and waiting for another. Break the cycle with one global lock order, or use
tryLockwith a timeout.jstackshows it as 'Found one Java-level deadlock'."
Bridge: ReentrantLock, one level down
synchronized is built into the language and releases itself. That is its strength, and also its limit: you cannot wait for it with a time limit, cannot give up, cannot be interrupted while waiting for it, and cannot check whether it is free. java.util.concurrent.locks.ReentrantLock is an ordinary object with the same mutual exclusion and visibility guarantees, plus those missing abilities. The price is that you must release it, always in a finally block.
synchronized
The monitor is taken and released by the language. Nothing to forget.
class SyncCounter {
private int n;
synchronized void inc() {
n++;
}
synchronized int get() {
return n;
}
}ReentrantLock
Explicit lock and unlock. More control, and one more thing to get right.
class LockedCounter {
final ReentrantLock lock =
new ReentrantLock();
private int n;
void inc() {
lock.lock();
try { n++; }
finally { lock.unlock(); }
}
}The shift: you trade automatic release for the power to wait with a timeout, to be interrupted, to poll, and to use several wait queues.
Here is the full program with both counters, both reaching 400,000.
import java.util.concurrent.locks.ReentrantLock;
public class LockCounter {
static class SyncCounter {
private int n;
synchronized void inc() { n++; }
synchronized int get() { return n; }
}
static class LockedCounter {
private final ReentrantLock lock = new ReentrantLock();
private int n;
void inc() {
lock.lock();
try { n++; } finally { lock.unlock(); } // finally: never forget
}
int get() {
lock.lock();
try { return n; } finally { lock.unlock(); }
}
}
static void hammer(Runnable r) throws Exception {
Thread[] ts = new Thread[4];
for (int i = 0; i < 4; i++) { ts[i] = new Thread(() -> { for (int k = 0; k < 100_000; k++) r.run(); }); ts[i].start(); }
for (Thread t : ts) t.join();
}
public static void main(String[] args) throws Exception {
SyncCounter s = new SyncCounter();
hammer(s::inc);
System.out.println("synchronized: " + s.get());
LockedCounter l = new LockedCounter();
hammer(l::inc);
System.out.println("ReentrantLock: " + l.get());
}
}synchronized: 400000
ReentrantLock: 400000Same total. The rule for the explicit lock is rigid: lock.lock(); then immediately try { ... } finally { lock.unlock(); }, with the lock call outside the try. If unlock is skipped by an exception, the lock stays held forever and every later caller blocks. The compiler will not warn you.
It is called reentrant for the same reason a monitor is: a thread that owns it can call lock() again and gets a hold count of 2. Each lock() must be matched by one unlock().
Idiom: tryLock with a timeout instead of waiting forever
The problem: a thread waits for a lock that another thread holds for a long time, for example a lock around a payment gateway that has stalled. With synchronized or lock() the waiting thread is stuck for as long as it takes, and a request thread, and perhaps a whole pool, goes with it.
How it works: tryLock(time, unit) waits up to the given time, then returns false instead of blocking more. The caller decides what to do: fall back, return an error, or try something else. tryLock() with no arguments answers immediately.
- Try:
if (lock.tryLock(1, TimeUnit.SECONDS)). - Got it: do the work inside
tryand release infinally. - Did not get it: take the fallback path. Never call
unlock()on this path, because you do not own the lock.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TryLockDemo {
static final ReentrantLock gateway = new ReentrantLock();
public static void main(String[] args) throws Exception {
Thread holder = new Thread(() -> {
gateway.lock();
try {
System.out.println("holder: has the payment-gateway lock, working for 3 s");
Thread.sleep(3000);
} catch (InterruptedException e) { }
finally { gateway.unlock(); }
}, "holder");
holder.start();
Thread.sleep(100);
long t0 = System.nanoTime();
System.out.println("main: tryLock(1 s) ...");
if (gateway.tryLock(1, TimeUnit.SECONDS)) {
try { System.out.println("main: got the lock"); } finally { gateway.unlock(); }
} else {
System.out.println("main: gave up after " + (System.nanoTime() - t0) / 1_000_000
+ " ms; owner is " + (gateway.isLocked() ? "someone else" : "nobody")
+ ", falling back to 'payment pending'");
}
// plain tryLock(): answer right now
System.out.println("tryLock() right now: " + gateway.tryLock());
// lockInterruptibly: can be cancelled while waiting
Thread waiter = new Thread(() -> {
try {
gateway.lockInterruptibly();
System.out.println("waiter: got it (unexpected)");
} catch (InterruptedException e) {
System.out.println("waiter: interrupted while waiting for the lock");
}
}, "waiter");
waiter.start();
Thread.sleep(200);
waiter.interrupt();
waiter.join();
holder.join();
}
}holder: has the payment-gateway lock, working for 3 s
main: tryLock(1 s) ...
main: gave up after 1000 ms; owner is someone else, falling back to 'payment pending'
tryLock() right now: false
waiter: interrupted while waiting for the lockThe holder kept the lock for 3 seconds. The main thread asked for it with a 1-second limit and gave up after exactly 1,000 ms, then took the fallback ("payment pending") instead of hanging. The bare tryLock() a moment later answered false at once. A third thread used lockInterruptibly(), which waits like lock() but throws InterruptedException if someone interrupts it. That is how you cancel a thread that is waiting for a lock, which synchronized cannot do.
tryLock also removes deadlocks as a side effect. If thread 1 holds A and fails to get B within a timeout, it can release A and try again later, which breaks the "holding while waiting" condition from the deadlock list. It is a cure, with a cost: you now have retry logic to write.
- Works: a bounded wait around slow shared resources; "skip this cycle if the previous one is still running" with
tryLock(); breaking possible deadlocks by timing out. - Fails: calling
unlock()after a failedtryLock(throwsIllegalMonitorStateException). Puttinglock()inside thetryblock. Ignoring thefalseresult. - Interview takeaway: "
synchronizedwaits forever.tryLock(timeout)lets a thread give up and do something else, andlockInterruptibly()lets it be cancelled while waiting."
Fairness has a price
new ReentrantLock(true) makes the lock fair: waiting threads get it in arrival order. The default lock is not fair. A thread that arrives at the moment the lock is released may barge in ahead of threads that have been waiting longer. Fairness prevents starvation but costs throughput, because each hand-off must wake the next thread in line.
The test: 8 threads each take the lock 20,000 times to increment a counter, fair and non-fair, after a warm-up.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
public class FairLock {
static long run(boolean fair) throws Exception {
ReentrantLock lock = new ReentrantLock(fair);
long[] total = new long[1];
CountDownLatch gate = new CountDownLatch(1);
Thread[] ts = new Thread[8];
for (int i = 0; i < ts.length; i++) {
ts[i] = new Thread(() -> {
try { gate.await(); } catch (InterruptedException e) { return; }
for (int k = 0; k < 20_000; k++) {
lock.lock();
try { total[0]++; } finally { lock.unlock(); }
}
});
ts[i].start();
}
long t0 = System.nanoTime();
gate.countDown();
for (Thread t : ts) t.join();
long ms = (System.nanoTime() - t0) / 1_000_000;
if (total[0] != 160_000) throw new AssertionError();
return ms;
}
public static void main(String[] args) throws Exception {
run(false); run(true); // warm-up
for (int round = 1; round <= 3; round++)
System.out.printf("round %d: non-fair %4d ms | fair %5d ms%n", round, run(false), run(true));
}
}round 1: non-fair 7 ms | fair 1592 ms
round 2: non-fair 2 ms | fair 1891 ms
round 3: non-fair 6 ms | fair 1833 msThe unfair lock finished 160,000 acquisitions in 2 to 7 ms (the last launch printed 7, 2 and 6). The fair lock took around 1.6 to 1.9 seconds, which is roughly 200 to 900 times slower on this contended test.
The unfair lock is fast partly because a thread that just released the lock can grab it again without a context switch, so one thread runs many iterations in a row. That is also exactly the starvation risk fairness addresses. Use a fair lock only when you have measured actual starvation, not by default.
Bridge: Condition, await and signal, one level down
A thread often needs to wait until something becomes true: "the queue is not empty", "there is room in the buffer". With synchronized the tools are wait() and notify(), and a monitor has only one wait set, so you cannot say who to wake. A ReentrantLock can create many Condition objects, each with its own wait set. A cook waits on "not empty", a producer waits on "not full", and you wake exactly the right kind.
A tiny bounded buffer: the kitchen can hold at most 3 waiting orders. The producer places 8 orders as fast as it can, and the cook takes one every 100 ms.
import java.util.*;
import java.util.concurrent.locks.*;
public class BoundedBuffer<T> {
private final Queue<T> items = new ArrayDeque<>();
private final int capacity;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition(); // producers wait here
private final Condition notEmpty = lock.newCondition(); // consumers wait here
BoundedBuffer(int capacity) { this.capacity = capacity; }
void put(T x) throws InterruptedException {
lock.lock();
try {
while (items.size() == capacity) notFull.await(); // while, not if
items.add(x);
notEmpty.signal();
} finally { lock.unlock(); }
}
T take() throws InterruptedException {
lock.lock();
try {
while (items.isEmpty()) notEmpty.await();
T x = items.remove();
notFull.signal();
return x;
} finally { lock.unlock(); }
}
public static void main(String[] args) throws Exception {
BoundedBuffer<Integer> kitchen = new BoundedBuffer<>(3); // at most 3 orders waiting
Thread producer = new Thread(() -> {
try {
for (int id = 1; id <= 8; id++) {
kitchen.put(id);
System.out.println("placed order " + id);
}
} catch (InterruptedException e) { }
}, "producer");
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 8; i++) {
Thread.sleep(100); // cooking is slow
System.out.println(" cooked order " + kitchen.take());
}
} catch (InterruptedException e) { }
}, "cook");
producer.start(); consumer.start();
producer.join(); consumer.join();
}
}placed order 1
placed order 2
placed order 3
placed order 4
cooked order 1
cooked order 2
placed order 5
cooked order 3
placed order 6
placed order 7
cooked order 4
placed order 8
cooked order 5
cooked order 6
cooked order 7
cooked order 8The producer placed orders 1, 2 and 3, and order 4 only once the cook had taken order 1 out of the buffer (the "cooked" line prints a moment after the take). Before that it stopped at the full buffer. It only continued as the cook took orders, one at a time. Every order was cooked in order, none was lost, and the producer never spun in a busy loop. await() releases the lock while the thread sleeps and takes it back before returning, exactly like wait().
Two details matter. Always call await() in a while loop that re-checks the condition, never in an if. A thread can be woken when the condition is no longer true (another consumer took the item first), and the JVM is allowed to wake a waiting thread spuriously, with no signal at all.
And call signal() while holding the lock. In real code you would use an ArrayBlockingQueue, which does all of this inside, as shown in the executors section. Writing a buffer by hand is how you learn what it does.
Bridge: ReadWriteLock, one level down
Many data structures are read far more often than they are written. A QuickBite menu cache is read on every order and refreshed once a minute. With an ordinary lock, readers wait for each other for no reason, because reading does not change anything. A ReentrantReadWriteLock has two sides: the read lock can be held by any number of threads at once, and the write lock is exclusive and also excludes all readers.
The test: 8 threads each look up the menu, which takes 100 ms. First behind one exclusive lock, then behind the read lock. After that a writer arrives while a reader is still working, to see what it does.
import java.util.*;
import java.util.concurrent.locks.*;
public class RWLockDemo {
static final Map<String, Integer> menu = new HashMap<>(Map.of("biryani", 24900, "raita", 4900));
static void lookup() { try { Thread.sleep(100); } catch (InterruptedException e) { } } // a slowish read
static long run(Runnable[] jobs) throws Exception {
Thread[] ts = new Thread[jobs.length];
for (int i = 0; i < jobs.length; i++) ts[i] = new Thread(jobs[i]);
long t0 = System.nanoTime();
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
ReentrantLock exclusive = new ReentrantLock();
ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
Runnable[] exclusiveReaders = new Runnable[8];
Runnable[] sharedReaders = new Runnable[8];
for (int i = 0; i < 8; i++) {
exclusiveReaders[i] = () -> { exclusive.lock(); try { menu.get("biryani"); lookup(); } finally { exclusive.unlock(); } };
sharedReaders[i] = () -> { rw.readLock().lock(); try { menu.get("biryani"); lookup(); } finally { rw.readLock().unlock(); } };
}
System.out.println("8 readers, ReentrantLock (one at a time): " + run(exclusiveReaders) + " ms");
System.out.println("8 readers, read lock (all together): " + run(sharedReaders) + " ms");
// a writer needs the lock alone: it waits for readers, and readers wait for it
Runnable writer = () -> {
long t0 = System.nanoTime();
rw.writeLock().lock();
try {
System.out.println("writer: got the write lock after " + (System.nanoTime() - t0) / 1_000_000 + " ms");
menu.put("biryani", 25900);
} finally { rw.writeLock().unlock(); }
};
Thread slowReader = new Thread(() -> { rw.readLock().lock(); try { Thread.sleep(300); } catch (InterruptedException e) { } finally { rw.readLock().unlock(); } });
slowReader.start();
Thread.sleep(50);
Thread w = new Thread(writer); w.start();
w.join(); slowReader.join();
System.out.println("new price: " + menu.get("biryani"));
}
}8 readers, ReentrantLock (one at a time): 807 ms
8 readers, read lock (all together): 100 ms
writer: got the write lock after 251 ms
new price: 25900Eight readers behind an exclusive lock took 807 ms, which is 8 × 100 plus overhead: they queued. Behind the read lock they took 100 ms: all eight ran together. The writer arrived 50 ms after a reader that held the lock for 300 ms, and got the write lock after 251 ms, which is exactly "wait for the reader to finish".
The Javadoc adds that, for the default non-fair lock, a new reader is held back when a writer is first in the queue, so a constant stream of readers does not starve the writer. (This run does not show that part.)
When is it worth it? Only when reads are much more common than writes and each read holds the lock for a meaningful time. For a 20-nanosecond map lookup, the book-keeping of a read-write lock costs more than it saves, and a plain lock or a ConcurrentHashMap is better.
There are two more catches. You cannot upgrade a read lock to a write lock while holding it (the thread deadlocks against itself), so release the read lock first. And a write lock can be downgraded to a read lock, which is the supported way to update and then keep reading.
Bridge: StampedLock and the optimistic read, one level down
StampedLock (Java 8) adds a third mode: the optimistic read. You ask for a stamp, a version number, without locking anything. You read the fields into local variables. Then you call validate(stamp). If no writer has run in between, the stamp is still valid, your copies are consistent, and you paid almost nothing. If a writer did run, validate returns false and you fall back to a proper read lock and read again.
import java.util.concurrent.locks.StampedLock;
public class StampedDemo {
static class Rider {
private final StampedLock sl = new StampedLock();
private double lat = 12.97, lon = 77.59; // two fields that must change together
void moveTo(double newLat, double newLon) {
long stamp = sl.writeLock();
try { lat = newLat; lon = newLon; } finally { sl.unlockWrite(stamp); }
}
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead(); // no lock taken, just a version number
double a = lat, b = lon; // copy to locals
if (!sl.validate(stamp)) { // did a writer run meanwhile?
System.out.println(" optimistic read was invalid, falling back to a real read lock");
stamp = sl.readLock();
try { a = lat; b = lon; } finally { sl.unlockRead(stamp); }
}
return Math.sqrt(a * a + b * b);
}
long peekStamp() { return sl.tryOptimisticRead(); }
boolean stillValid(long s) { return sl.validate(s); }
}
public static void main(String[] args) throws Exception {
Rider r = new Rider();
System.out.printf("distance: %.4f%n", r.distanceFromOrigin());
long s = r.peekStamp();
System.out.println("stamp valid before any write: " + r.stillValid(s));
r.moveTo(13.00, 77.60);
System.out.println("stamp valid after a write: " + r.stillValid(s));
// StampedLock is not reentrant: taking the write lock twice in one thread blocks forever
StampedLock sl = new StampedLock();
sl.writeLock();
System.out.println("second writeLock() by the same thread would block; tryWriteLock() says: "
+ sl.tryWriteLock());
System.out.println("distance now: " + String.format("%.4f", r.distanceFromOrigin()));
}
}distance: 78.6666
stamp valid before any write: true
stamp valid after a write: false
second writeLock() by the same thread would block; tryWriteLock() says: 0
distance now: 78.6814The stamp was valid until a write happened and invalid afterwards. The last two lines show a sharp edge: tryWriteLock() returned 0, which means failure, because the thread already held that write lock and this lock is not reentrant. The plain writeLock() in that position would have blocked the thread forever, with no error.
The sharp edges, listed together. StampedLock is not reentrant. It has no Condition. A stamp must be passed back to the matching unlock call, so lost stamps mean lost locks. Everything read optimistically is only trustworthy after validate returns true, so copy fields to locals first and never act on them (call methods, throw, index arrays) before validating. It is a specialist tool for read-heavy structures with tiny read sections, such as a point or a counter pair. Reach for it after a profiler shows lock cost, not before.
Bridge: wait and notify, in two paragraphs
The oldest coordination tool in Java is on Object. A thread that holds an object's monitor calls wait(): it joins the wait set, gives up the monitor and sleeps. Another thread, holding the same monitor, changes the state and calls notify() (wake one waiter) or notifyAll() (wake all). The woken thread must re-acquire the monitor before continuing. It must always wait in a loop that re-checks its condition.
import java.util.*;
public class WaitNotifyDemo {
static final Object monitor = new Object();
static final Queue<Integer> orders = new ArrayDeque<>();
public static void main(String[] args) throws Exception {
Thread cook = new Thread(() -> {
synchronized (monitor) {
while (orders.isEmpty()) { // always re-check in a loop
try { monitor.wait(); } // releases the monitor, sleeps
catch (InterruptedException e) { return; }
}
System.out.println("cook: took order " + orders.remove());
}
});
cook.start();
Thread.sleep(200);
System.out.println("cook state while waiting: " + cook.getState());
synchronized (monitor) {
orders.add(7);
monitor.notify(); // wake one waiter
}
cook.join();
}
}cook state while waiting: WAITING
cook: took order 7The cook thread was in state WAITING (the state table above), then the order arrived, notify() woke it, and it took the order. This works and is correct, but it is easy to get wrong: calling wait outside synchronized throws IllegalMonitorStateException; using if in place of while loses to spurious wake-ups; calling notify when several kinds of waiters share one monitor can wake the wrong one and leave the right one sleeping forever.
That is why modern code uses java.util.concurrent (BlockingQueue, Condition, CountDownLatch) instead of writing its own. E3 has the full interview treatment in Q159–Q165.
Choosing a synchronization tool
The stack rule for this section: for each shared piece of state, pick the lightest tool that makes the whole operation correct, then say when you would switch.
| Option | Pick it when | Cost or catch |
|---|---|---|
volatile | One thread writes, others read a single field (stop flag, published config). | No atomicity. count++ still races. No mutual exclusion. |
synchronized | Default for guarding a few fields or an invariant across several. Small critical sections. | No timeout, no interrupt while waiting. One wait set per monitor. Cost is unpredictable under heavy contention (246 to 2,727 ms above). |
ReentrantLock | You need tryLock, a timeout, interruptible waits, several conditions, or fairness. | You must unlock in finally. Fair mode was hundreds of times slower in our test. |
ReentrantReadWriteLock | Reads are far more common than writes and each read takes real time (cache with slow lookups). | Bookkeeping overhead; no read-to-write upgrade; writers can wait on long reads. |
StampedLock | Read-heavy, tiny read sections, measured lock cost; optimistic reads of a few fields. | Not reentrant, no conditions, stamps to manage, easy to misuse. |
Atomic* | One variable with read-modify-write: counters, sequence numbers, a maximum, a swapped reference. | One variable only. Retries under heavy contention (452,532 in our run). Update functions must be free of side effects. |
LongAdder | Very hot counters or metrics, read now and then. | Not an exact snapshot during updates; no compare-and-set; more memory. |
When to switch: if a synchronized method is hot and only protects one number, move to an atomic. If a counter is the hottest thing in a profile, move to LongAdder. If you need a timeout or a second condition, move to ReentrantLock. If the data is read-mostly and a profiler shows readers blocking each other, try the read-write lock. If the structure is a map or queue, skip all of this and use a ConcurrentHashMap or BlockingQueue from the next section.
One last point about this whole section. Locks are for shared mutable state. The simplest correct code often avoids both words: keep data immutable, confine each piece of data to one thread, or hand finished results from thread to thread through a queue or a Future. Everything above is what you use when you cannot. E3 drills these tools further, starting at its concurrency chapter, and E2 gives the memory-model detail underneath.
10 · Executors, Callable, Future and the coordination toolkitExecutors, Callable and Future, and the Coordination Toolkit
An executor is a pool of worker threads plus a queue of waiting tasks, so you stop creating one thread per job. You hand it a task, you get back a Future (a ticket for the result), and the pool decides when and where the task runs. Around that core sit five small tools (latch, barrier, semaphore, blocking queue, concurrent map) that cover most coordination needs without wait and notify.
Back to QuickBite. The notification service sends an SMS and a push message for every order. Its first version was the obvious one: for each order, new Thread(() -> notifyCustomer(order)).start(). It worked in testing and it worked at 500 orders a minute.
At 20,000 orders a minute, on the busiest Friday, the service died with java.lang.OutOfMemoryError: unable to create native thread. The heap was fine. The operating system had simply refused to create more threads. Each platform thread (a thread that the operating system schedules) reserves a stack, often 1 MB of address space, and the machine has a limit on how many threads may exist.
The fix was three lines: one shared pool of 16 threads, and pool.submit(...) instead of new Thread(...). We will not try to crash this machine. Instead we measure a safe miniature: 10,000 tiny tasks, once with a new thread each and once through a pool of 16.
Make the invisible visible: what a thread costs. Each task only adds 1 to a counter, so any time we measure is the cost of the threads themselves. Round 1 warms up the JIT compiler (the part of the JVM that turns hot code into machine code).
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadsVsPool {
static final AtomicInteger sent = new AtomicInteger();
static void notifyCustomer() { sent.incrementAndGet(); } // pretend: tiny work
public static void main(String[] args) throws Exception {
int n = 10_000;
for (int round = 1; round <= 2; round++) { // round 1 warms up the JIT
sent.set(0);
long t0 = System.nanoTime();
Thread[] ts = new Thread[n];
for (int i = 0; i < n; i++) { ts[i] = new Thread(ThreadsVsPool::notifyCustomer); ts[i].start(); }
for (Thread t : ts) t.join();
long ms1 = (System.nanoTime() - t0) / 1_000_000;
sent.set(0);
t0 = System.nanoTime();
try (ExecutorService pool = Executors.newFixedThreadPool(16)) {
for (int i = 0; i < n; i++) pool.submit(ThreadsVsPool::notifyCustomer);
} // close() waits for the queue to drain
long ms2 = (System.nanoTime() - t0) / 1_000_000;
System.out.printf("round %d: new Thread x %d = %d ms | 16-thread pool, %d tasks = %d ms (sent=%d)%n",
round, n, ms1, n, ms2, sent.get());
}
}
}# measured on the course machine (12 cores); your numbers will differ
round 1: new Thread x 10000 = 860 ms | 16-thread pool, 10000 tasks = 25 ms (sent=10000)
round 2: new Thread x 10000 = 882 ms | 16-thread pool, 10000 tasks = 8 ms (sent=10000)What you see: 10,000 new threads took about 860 ms. The same 10,000 tasks through 16 pooled threads took 8 to 25 ms. That is 35 to 100 times faster, and the pool kept only 16 threads alive instead of creating and destroying 10,000.
Why: starting a thread asks the operating system for a stack and a kernel object. Finishing it gives them back. A pool pays that cost 16 times in total, then reuses each worker for hundreds of tasks. The numbers are from a machine that was also busy with other work, so treat them as a ratio, not a promise.
The program uses two ideas you have not met formally. Executors.newFixedThreadPool(16) builds the pool. The try (ExecutorService pool = ...) block is allowed since Java 19, and leaving the block waits for every queued task to finish. We come back to that in the shutdown section.
Bridge: ExecutorService, one level down
An executor is an object that runs tasks for you. The interface Executor has one method, execute(Runnable). ExecutorService extends it with submit, invokeAll, invokeAny and the shutdown methods. A task is a small piece of work: a Runnable (no result) or a Callable (returns a result).
Inside the common implementation, ThreadPoolExecutor, there are only two parts: a set of worker threads, and a work queue. A worker thread runs a simple loop: take a task from the queue, run it, take the next one. When no task is available, the worker waits.
The interesting part is what happens when a task arrives. The pool has a strict order of questions, and the order surprises almost everyone the first time. Figure 21.14 shows it.
Read the figure twice. The order is core thread, then queue, then extra thread, then rejection. Many developers assume that "maximum pool size" means the pool grows as load grows. It does not. With an unbounded queue, step 2 never says "no", so steps 3 and 4 never happen and the maximum is ignored. We will break a pool exactly this way in a few pages.
Now the two ways to give a pool work. execute(Runnable) is fire and forget: it returns nothing. submit(...) accepts a Runnable or a Callable and returns a Future. The difference matters most when the task throws.
Make the invisible visible: the same exception thrown from execute and from submit. A pool with one thread runs two tasks that each throw a RuntimeException.
import java.util.concurrent.*;
public class ExecuteVsSubmit {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.execute(() -> { throw new RuntimeException("boom from execute"); });
Thread.sleep(200);
Future<?> f = pool.submit(() -> { throw new RuntimeException("boom from submit"); });
Thread.sleep(200);
System.out.println("submit: nothing printed above this line, f.isDone()=" + f.isDone());
try { f.get(); } catch (ExecutionException e) { System.out.println("only get() tells you: " + e.getCause()); }
pool.shutdown();
}
}Exception in thread "pool-1-thread-1" java.lang.RuntimeException: boom from execute
at ExecuteVsSubmit.lambda$main$0(ExecuteVsSubmit.java:7)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)
at java.base/java.lang.Thread.run(Thread.java:1474)
submit: nothing printed above this line, f.isDone()=true
only get() tells you: java.lang.RuntimeException: boom from submitWhat you see: execute printed a stack trace on standard error, because the exception escaped the worker thread and reached the thread's uncaught exception handler. submit printed nothing at all. The exception was caught by the Future and stored there. It comes out only when somebody calls get().
That is the single most common executor bug: pool.submit(task) with the returned Future thrown away. The task fails, the failure is stored in an object nobody holds, and the logs stay clean. If you do not need the result, either use execute, or wrap the task body in a try/catch that logs. Link: E3's concurrency drill asks this as a question about exceptions in pools.
Bridge: Callable and Future, one level down
A Runnable has void run(). It cannot return a value and it cannot throw a checked exception. A Callable<V> has V call() throws Exception. It returns a value and may throw anything. That is the whole difference, and it is why Callable is the type for "compute something and give it back".
A Future<V> is the ticket you get when you submit a task. The result does not exist yet, so the future is a placeholder. It has five methods you need.
get(): waits until the task finishes, then returns the value. If the task threw,get()throwsExecutionExceptionwith the original exception as its cause.get(time, unit): the same, but gives up withTimeoutExceptionafter the wait. The task itself keeps running.cancel(true): tries to stop the task. If it is running, its thread is interrupted.truemeans "interrupt it";falsemeans "only prevent it from starting".isDone(),isCancelled(): non-blocking questions about the state.
Runnable + shared variable
The result travels through a variable that both threads can see. You must also join, and exceptions are lost.
// illustrative
int[] box = new int[1];
Thread t = new Thread(() -> {
box[0] = loadMenu();
});
t.start();
t.join(); // wait, or box is 0
use(box[0]);Callable + Future
The result is the return value. The failure, if any, comes back from get().
// illustrative
Future<Integer> f =
pool.submit(() -> loadMenu());
// ... do other work here ...
int menu = f.get(); // waits if needed
use(menu);The shift: instead of smuggling the result out through shared memory and a join, the task returns it and the future carries it, success or failure.
Make the invisible visible: all four behaviours of a Future in one run: blocking get, a timeout, a cancel, and an exception inside the task. The sleeps stand in for the QuickBite services.
import java.util.concurrent.*;
public class FutureBasics {
static String slow(String what, int ms) throws InterruptedException {
Thread.sleep(ms);
return what + " done";
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
// 1. get() blocks until the task finishes
long t0 = System.nanoTime();
Future<String> f = pool.submit(() -> slow("menu", 300));
System.out.println("submitted after " + ms(t0) + " ms, isDone=" + f.isDone());
System.out.println("get() -> " + f.get() + " after " + ms(t0) + " ms");
// 2. get(timeout) gives up waiting (the task keeps running)
Future<String> g = pool.submit(() -> slow("rider ETA", 800));
try {
g.get(200, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
System.out.println("get(200ms) -> TimeoutException, isDone=" + g.isDone());
}
// 3. cancel(true) interrupts the running task
boolean cancelled = g.cancel(true);
System.out.println("cancel(true) -> " + cancelled + ", isCancelled=" + g.isCancelled());
try { g.get(); } catch (CancellationException e) { System.out.println("get() after cancel -> " + e); }
// 4. an exception inside the task comes back wrapped
Future<Integer> bad = pool.submit(() -> {
if (true) throw new IllegalStateException("price service returned 500");
return 1;
});
try {
bad.get();
} catch (ExecutionException e) {
System.out.println("get() -> " + e);
System.out.println("getCause() -> " + e.getCause());
}
pool.shutdown();
}
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
}submitted after 1 ms, isDone=false
get() -> menu done after 304 ms
get(200ms) -> TimeoutException, isDone=false
cancel(true) -> true, isCancelled=true
get() after cancel -> java.util.concurrent.CancellationException
get() -> java.util.concurrent.ExecutionException: java.lang.IllegalStateException: price service returned 500
getCause() -> java.lang.IllegalStateException: price service returned 500What you see: submit returned after 1 ms, and get() returned after 304 ms: the 300 ms is the task's sleep, the 4 ms is overhead. get(200 ms) gave up while the task was still not done. cancel(true) returned true, and a later get() threw CancellationException. The failing task came back as an ExecutionException whose message starts with the cause's class name and whose getCause() is the real exception.
Two details are easy to miss. After a timeout, the task is still running, so a timeout alone does not free the thread. Call cancel(true) as well, and write the task so that it reacts to interruption (a Thread.sleep or blocking queue call already does). And always unwrap ExecutionException: the useful information is in getCause().
Idiom: Callable and Future, with a timeout and an unwrap
The problem: a task is submitted and its Future is ignored, so failures vanish. Or get() is called with no timeout, so one slow service freezes the calling thread forever.
How it works: a Future is the only place a task's result or failure is stored. Holding it and asking it correctly is part of the contract of submit.
- Keep the future: assign the return value of
submitto a variable, even if you read it later. - Always bound the wait: use
get(timeout, unit), with a number that comes from the caller's own deadline. - Unwrap and cancel: catch
ExecutionExceptionand usegetCause(); on timeout callcancel(true).
// illustrative: the real run is ExecuteVsSubmit above
pool.submit(() -> { throw new RuntimeException("boom from submit"); });
// no get(): the failure is stored in a Future nobody holds
// output: nothing at all// illustrative: the pieces are run in FutureBasics above
String eta;
Future<String> f = pool.submit(() -> riderEta());
try {
eta = f.get(500, TimeUnit.MILLISECONDS); // bounded wait
} catch (TimeoutException e) {
f.cancel(true); // free the worker
eta = "about 30 min";
} catch (ExecutionException e) {
log.error("rider service failed", e.getCause()); // the real error
eta = "about 30 min";
}- Works: a bounded
getthat turns a slow dependency into a fallback value, and an unwrapped cause that shows up in the log. - Fails:
cancel(true)cannot stop code that ignores interruption (a tight CPU loop never notices). And aget()inside a pool task that waits for another task in the same pool can deadlock when every worker is waiting. - Interview takeaway: "A Future stores either the value or the exception. I keep it, I bound the wait, I unwrap ExecutionException, and I cancel on timeout."
Bridge: invokeAll and invokeAny, one level down
Often you have several independent calls and one decision to make after they are done. invokeAll(tasks) submits every Callable, waits for all of them, and returns a list of futures in the same order. invokeAny(tasks) returns the result of the first task that succeeds and cancels the rest.
QuickBite's checkout needs the menu (300 ms), the price (250 ms) and the rider's ETA (350 ms). Done one after another that is 300 + 250 + 350 = 900 ms. Done at the same time it should cost the slowest one, 350 ms.
import java.util.*;
import java.util.concurrent.*;
public class InvokeAllAny {
static String menu() throws Exception { Thread.sleep(300); return "menu"; }
static String price() throws Exception { Thread.sleep(250); return "price"; }
static String riderEta() throws Exception { Thread.sleep(350); return "eta"; }
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
System.out.println(menu() + " " + price() + " " + riderEta() + " sequential: " + ms(t0) + " ms");
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
List<Callable<String>> calls = List.of(InvokeAllAny::menu, InvokeAllAny::price, InvokeAllAny::riderEta);
t0 = System.nanoTime();
List<Future<String>> all = pool.invokeAll(calls); // waits for ALL
StringBuilder sb = new StringBuilder();
for (Future<String> f : all) sb.append(f.get()).append(' ');
System.out.println(sb + "invokeAll: " + ms(t0) + " ms");
t0 = System.nanoTime();
String first = pool.invokeAny(calls); // first SUCCESS wins, rest cancelled
System.out.println(first + " invokeAny: " + ms(t0) + " ms");
List<Callable<String>> mixed = List.of(
() -> { throw new IllegalStateException("mirror A is down"); },
() -> { Thread.sleep(100); return "mirror B"; });
System.out.println("invokeAny with one failing task -> " + pool.invokeAny(mixed));
}
}
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
}# measured on the course machine (12 cores); your numbers will differ
menu price eta sequential: 900 ms
menu price eta invokeAll: 351 ms
price invokeAny: 251 ms
invokeAny with one failing task -> mirror BWhat you see: sequential took 900 ms. invokeAll took 351 ms, which is the slowest task plus 1 ms. invokeAny returned price after 251 ms, because the 250 ms task finished first and the other two were cancelled. In the last line one task threw and the other succeeded, and invokeAny returned the success: failed tasks are ignored unless all of them fail.
Use invokeAll when you need every result. Use invokeAny for "ask three mirrors, take the fastest answer". Both block the calling thread, so for the checkout flow we will later prefer CompletableFuture, which does the same without parking a thread.
Bridge: ThreadPoolExecutor parameters, one level down
Every ready-made pool from Executors is a ThreadPoolExecutor with fixed settings. Knowing the constructor lets you choose the settings yourself. There are seven parameters, and Figure 21.14 shows where each one acts.
| Parameter | What it controls | Typical value |
|---|---|---|
corePoolSize | Threads kept alive even when idle. Step 1 of the figure. | Cores for CPU work; more for waiting work |
maximumPoolSize | Upper limit, reached only when the queue is full. Step 3. | Equal to core, or a small multiple |
keepAliveTime | How long an extra thread may sit idle before it exits. | 30 to 60 seconds |
workQueue | Where tasks wait. Its type decides the whole behaviour. Step 2. | ArrayBlockingQueue(100) |
threadFactory | Creates the threads. Where you set names and daemon status. | Named threads |
handler | What to do when the task is rejected. Step 4. | CallerRunsPolicy or abort |
The factory methods hide these choices, and two of them hide a trap. newFixedThreadPool(n) is a pool with core = max = n and an unbounded LinkedBlockingQueue (its capacity is Integer.MAX_VALUE, about 2.1 billion). newCachedThreadPool() uses a SynchronousQueue (no storage at all) and a maximum of Integer.MAX_VALUE threads, so it can create thousands of threads under load.
The trap: an unbounded queue never says "no". When the downstream service is slower than the arrival rate, the queue just grows. There is no error, no rejection, no back-pressure (a signal that tells the sender to slow down). The only symptom is memory, until the heap is gone.
Make the invisible visible: a fixed pool of 2 threads whose workers are stuck (a slow downstream, simulated with a latch). The loop submits 1,000,000 tasks, each holding 64 bytes, and prints the queue size and heap use. Then a second run with 2 KB per task on a 64 MB heap shows how it ends. Both runs are small and safe.
import java.util.concurrent.*;
public class UnboundedQueue {
static long usedMb() { Runtime r = Runtime.getRuntime(); return (r.totalMemory() - r.freeMemory()) >> 20; }
public static void main(String[] args) throws Exception {
int payload = Integer.parseInt(args[0]); // bytes held by each queued task
int total = Integer.parseInt(args[1]);
int interval = Integer.parseInt(args[2]);
System.out.println("max heap = " + (Runtime.getRuntime().maxMemory() >> 20) + " MB");
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
CountDownLatch gate = new CountDownLatch(1); // workers stuck: the downstream is slow
int i = 0;
try {
for (i = 1; i <= total; i++) {
byte[] order = new byte[payload]; // the "order" waiting in the queue
pool.submit(() -> { gate.await(); return order.length; });
if (i % interval == 0)
System.out.printf("submitted %,9d | queue size %,9d | heap used %d MB | threads %d%n",
i, pool.getQueue().size(), usedMb(), pool.getPoolSize());
}
System.out.println("all " + total + " accepted, no error, no back-pressure");
} catch (OutOfMemoryError e) {
pool.getQueue().clear(); // free the heap first, then report
System.out.println("OutOfMemoryError: " + e.getMessage());
System.out.println("it hit on task number " + i + " of " + total);
} finally {
pool.shutdownNow();
}
}
}$ java -Xmx256m UnboundedQueue.java 64 1000000 250000
max heap = 256 MB
submitted 250,000 | queue size 249,998 | heap used 42 MB | threads 2
submitted 500,000 | queue size 499,998 | heap used 83 MB | threads 2
submitted 750,000 | queue size 749,998 | heap used 125 MB | threads 2
submitted 1,000,000 | queue size 999,998 | heap used 169 MB | threads 2
all 1000000 accepted, no error, no back-pressure
$ java -Xmx64m UnboundedQueue.java 2048 1000000 5000
max heap = 64 MB
submitted 5,000 | queue size 4,998 | heap used 14 MB | threads 2
submitted 10,000 | queue size 9,998 | heap used 25 MB | threads 2
submitted 15,000 | queue size 14,998 | heap used 35 MB | threads 2
submitted 20,000 | queue size 19,998 | heap used 47 MB | threads 2
submitted 25,000 | queue size 24,998 | heap used 61 MB | threads 2
OutOfMemoryError: Java heap space
it hit on task number 29186 of 1000000What you see: all 1,000,000 submissions were accepted. The queue held 999,998 tasks (1,000,000 minus the 2 running), the pool stayed at 2 threads, and the heap grew linearly to 169 MB. In the second run each queued order carried 2 KB, and the 64 MB heap ran out at task 29,186. Nothing refused any task before the memory did.
In production the queue would hold real orders, perhaps 5 KB each, and it would fill while the service looked healthy: threads busy, CPU low, latency growing without bound because a task at the back of a million-item queue waits hours. That is why a bounded queue plus a rejection policy is the standard answer.
Idiom: a bounded pool with a rejection policy
The problem: newFixedThreadPool and its unbounded queue accept work faster than they can finish it, and the queue eats the heap. newCachedThreadPool does the opposite and creates a thread for every burst.
How it works: build a ThreadPoolExecutor yourself with a queue that has a fixed capacity. When both the queue and the pool are full, step 4 of Figure 21.14 runs, and you choose the handler.
- Pick sizes from the work: a core size from the number of cores (CPU work) or from your downstream limit (waiting work), and a queue capacity small enough to hold seconds of work, not hours.
- Pick the handler:
AbortPolicy(default) throwsRejectedExecutionException;CallerRunsPolicymakes the submitting thread run the task itself, which slows the producer down (natural back-pressure);DiscardPolicyandDiscardOldestPolicydrop silently, which is only right for data you can lose. - Alert on rejections: a rejection is a signal that you are over capacity. Count it.
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class BoundedPool {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 4, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100), // bounded queue: at most 100 waiting
new ThreadPoolExecutor.CallerRunsPolicy()); // full? the submitter does the work itself
AtomicInteger byMain = new AtomicInteger(), byPool = new AtomicInteger();
long t0 = System.nanoTime();
int maxQueue = 0;
for (int i = 1; i <= 1_000; i++) {
pool.execute(() -> {
(Thread.currentThread().getName().equals("main") ? byMain : byPool).incrementAndGet();
try { Thread.sleep(5); } catch (InterruptedException e) { }
});
maxQueue = Math.max(maxQueue, pool.getQueue().size());
}
pool.shutdown();
pool.awaitTermination(30, TimeUnit.SECONDS);
System.out.println("1000 tasks done in " + (System.nanoTime() - t0) / 1_000_000 + " ms");
System.out.println("largest queue seen: " + maxQueue + " (limit 100), largest pool: " + pool.getLargestPoolSize());
System.out.println("run by pool threads: " + byPool + ", run by main (CallerRuns): " + byMain);
}
}# measured on the course machine (12 cores); your numbers will differ
1000 tasks done in 1065 ms
largest queue seen: 100 (limit 100), largest pool: 4
run by pool threads: 820, run by main (CallerRuns): 180What you see: the queue never went above its limit of 100, and the pool grew from its core size of 2 to its maximum of 4, but only after the queue filled up, exactly as Figure 21.14 says. 180 of the 1,000 tasks ran on main: when the pool and queue were full, CallerRunsPolicy made the submitting thread work, so it could not submit faster than the pool could drain.
Sanity check on the time: 1,000 tasks of 5 ms is 5,000 ms of work. Four pool threads plus the caller give about 5 workers, and 5,000 / 5 = 1,000 ms. The run took 1,065 ms. The arithmetic matches.
- Works: memory stays flat, the producer slows down instead of the heap growing, and the maximum pool size actually matters because the queue can fill.
- Fails:
CallerRunsPolicyfrom inside a request thread means a request thread now runs background work, so latency of that request rises. AndCallerRunsPolicydoes not help a task that must not run on the caller (for example, one that needs a special thread). Size choices need measurement; E3 Q181 to Q188 cover sizing and policies in depth. - Interview takeaway: "newFixedThreadPool has an unbounded queue, so it hides overload until the heap runs out. I build a ThreadPoolExecutor with a bounded queue and a rejection policy, and I count the rejections."
Bridge: sizing a pool, with arithmetic
"How many threads?" has two honest answers, depending on what the threads do. For CPU-bound tasks, extra threads only fight over cores, so use about the number of cores (12 here). For tasks that wait, a thread is idle most of the time, so you can afford more.
A rule of thumb for waiting work: threads = cores x (1 + wait time / compute time). A task that computes for 10 ms and waits 190 ms on a database has a ratio of 19, so 12 cores x 20 = 240 threads keep the cores busy.
A better number comes from Little's law: the number of tasks in progress equals the arrival rate times the time each takes. QuickBite's notifications arrive at 20,000 per minute, which is 333 per second. If each call takes 200 ms, then 333 x 0.2 = about 67 tasks are in progress at any moment, so 67 busy threads are needed, and a pool of 16 would fall behind.
Both formulas give starting points. Measure under load and watch the queue length: a queue that keeps growing means the pool is too small, and a queue that stays empty with idle threads means it is too large. E3 Q181 to Q188 go deeper.
One more way to hurt a pool does not involve size at all. A task that submits another task to the same pool and then waits for it holds a worker while it waits. If every worker is doing that, nobody is left to run the inner tasks. This is thread starvation deadlock. The program below uses timeouts so that it cannot hang.
import java.util.concurrent.*;
public class PoolStarvation {
static String run(int poolSize) throws Exception {
try (ExecutorService pool = Executors.newFixedThreadPool(poolSize)) {
Future<String> outer = pool.submit(() -> {
Future<String> inner = pool.submit(() -> "inner result"); // needs a free worker
return "outer got " + inner.get(1, TimeUnit.SECONDS); // but this worker waits for it
});
try { return outer.get(3, TimeUnit.SECONDS); }
catch (ExecutionException e) { return "outer failed: " + e.getCause().getClass().getSimpleName(); }
}
}
public static void main(String[] args) throws Exception {
System.out.println("pool of 1: " + run(1));
System.out.println("pool of 2: " + run(2));
}
}pool of 1: outer failed: TimeoutException
pool of 2: outer got inner resultWhat you see: with a pool of 1, the outer task occupied the only worker and waited for an inner task that could never start, and the wait ended only because of the 1-second timeout. With a pool of 2 it worked.
The danger is that it works in tests with a big pool and deadlocks in production when load makes every worker an outer task. The fixes: do not wait for subtasks inside the same pool, use a separate pool for the inner work, or compose with CompletableFuture so nothing waits.
Bridge: shutting a pool down, one level down
The workers of a pool are normal threads. Unless they are daemon threads, a pool that is never shut down keeps the JVM alive forever, even after main returns. Shutdown is a request in two flavours.
shutdown(): stop accepting new tasks (further submits throwRejectedExecutionException) but finish everything already accepted, running and queued.awaitTermination(time, unit): block until the pool has finished, or the time runs out. It returnstruewhen everything finished.shutdownNow(): interrupt the running tasks and return the list of tasks that never started. Tasks must handle the interrupt to stop early.
Since Java 19, ExecutorService implements AutoCloseable, so a try-with-resources block does the standard dance for you. close() calls shutdown() and waits, and if the waiting thread itself is interrupted it calls shutdownNow(). First the compile proof that this is a Java 19 feature.
import java.util.concurrent.*;
public class TryPool {
public static void main(String[] args) {
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
pool.submit(() -> System.out.println("hello from " + Thread.currentThread().getName()));
}
}
}$ javac --release 18 TryPool.java
TryPool.java:5: error: incompatible types: try-with-resources not applicable to variable type
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
^
(ExecutorService cannot be converted to AutoCloseable)
1 error
$ javac --release 19 TryPool.java
(compiles)Make the invisible visible: the three ways side by side, with a one-thread pool and slow tasks.
import java.util.concurrent.*;
public class ShutdownDemo {
static Runnable job(String name, int ms) {
return () -> {
try { Thread.sleep(ms); System.out.println(" " + name + " finished"); }
catch (InterruptedException e) { System.out.println(" " + name + " INTERRUPTED"); }
};
}
public static void main(String[] args) throws Exception {
System.out.println("1. shutdown() + awaitTermination: finish what was accepted");
ExecutorService a = Executors.newFixedThreadPool(1);
a.submit(job("A1", 300)); a.submit(job("A2", 300));
a.shutdown();
try { a.submit(job("A3", 10)); } catch (RejectedExecutionException e) { System.out.println(" new task rejected after shutdown()"); }
System.out.println(" terminated in time? " + a.awaitTermination(2, TimeUnit.SECONDS));
System.out.println("2. shutdownNow(): interrupt running, return the never-started");
ExecutorService b = Executors.newFixedThreadPool(1);
b.submit(job("B1", 1000)); b.submit(job("B2", 1000)); b.submit(job("B3", 1000));
Thread.sleep(100);
System.out.println(" never started: " + b.shutdownNow().size());
b.awaitTermination(2, TimeUnit.SECONDS);
System.out.println("3. try-with-resources (Java 19+): close() = shutdown + wait");
try (ExecutorService c = Executors.newFixedThreadPool(1)) {
c.submit(job("C1", 200)); c.submit(job("C2", 200));
}
System.out.println(" after the block, everything has finished");
}
}1. shutdown() + awaitTermination: finish what was accepted
new task rejected after shutdown()
A1 finished
A2 finished
terminated in time? true
2. shutdownNow(): interrupt running, return the never-started
never started: 2
B1 INTERRUPTED
3. try-with-resources (Java 19+): close() = shutdown + wait
C1 finished
C2 finished
after the block, everything has finishedWhat you see: after shutdown() the new task was rejected, but both accepted tasks finished and awaitTermination returned true. shutdownNow() returned 2 never-started tasks (B2 and B3) and interrupted the running one (B1). The try-with-resources block waited for both tasks before the next line ran.
Idiom: clean shutdown
The problem: a pool that is never closed keeps the process alive, and a pool that is killed with shutdownNow too early loses accepted work.
How it works: graceful first, forceful second, always bounded.
- Own the pool: create it in a try-with-resources block if its lifetime is one method (Java 19+).
- For a long-lived pool: call
shutdown(), thenawaitTerminationwith a deadline. - If the deadline passes: call
shutdownNow()and wait once more. Log how many tasks were returned.
// illustrative: the building blocks are run in ShutdownDemo above
pool.shutdown(); // no new tasks
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) { // bounded wait
List<Runnable> dropped = pool.shutdownNow(); // interrupt the rest
log.warn("forced stop, {} tasks never ran", dropped.size());
pool.awaitTermination(5, TimeUnit.SECONDS);
}- Works: accepted orders are finished, the JVM can exit, and the exit time is bounded.
- Fails:
shutdownNowonly helps tasks that respond to interrupts. A task stuck in a tight loop or in non-interruptible I/O keeps its thread. Also, never share one pool between unrelated parts of an app and let one of them shut it down. - Interview takeaway: "shutdown, then awaitTermination with a deadline, then shutdownNow. From Java 19 the executor is AutoCloseable, so try-with-resources does the first two steps."
Bridge: scheduled executors, one level down
A ScheduledExecutorService runs tasks later or repeatedly. schedule(task, delay) runs once. scheduleAtFixedRate(task, initialDelay, period, unit) runs every period, measured from start to start. scheduleWithFixedDelay waits the delay after each run finishes. QuickBite uses them for jobs such as "refresh the restaurant menu cache every minute".
There is one rule in the documentation that people read only after an incident: if any execution of the task throws an exception, later executions are suppressed. The job does not crash and does not log. It just never runs again.
Make the invisible visible: a job that ticks every 200 ms and throws on tick 3. We wait 1.5 seconds. Then the same job with its body wrapped in try/catch.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ScheduledDemo {
public static void main(String[] args) throws Exception {
ScheduledExecutorService s = Executors.newScheduledThreadPool(1);
AtomicInteger n = new AtomicInteger();
ScheduledFuture<?> f = s.scheduleAtFixedRate(() -> {
int tick = n.incrementAndGet();
System.out.println("unprotected tick " + tick);
if (tick == 3) throw new IllegalStateException("price feed hiccup");
}, 0, 200, TimeUnit.MILLISECONDS);
Thread.sleep(1500);
System.out.println("after 1.5 s: ticks=" + n + ", isDone=" + f.isDone());
try { f.get(); } catch (ExecutionException e) { System.out.println("the exception was waiting inside the future: " + e.getCause()); }
AtomicInteger m = new AtomicInteger();
s.scheduleAtFixedRate(() -> {
try {
int tick = m.incrementAndGet();
System.out.println("protected tick " + tick);
if (tick == 3) throw new IllegalStateException("price feed hiccup");
} catch (Exception e) {
System.out.println(" logged and carried on: " + e.getMessage());
}
}, 0, 200, TimeUnit.MILLISECONDS);
Thread.sleep(1500);
s.shutdownNow();
System.out.println("after 1.5 s: ticks=" + m);
}
}unprotected tick 1
unprotected tick 2
unprotected tick 3
after 1.5 s: ticks=3, isDone=true
the exception was waiting inside the future: java.lang.IllegalStateException: price feed hiccup
protected tick 1
protected tick 2
protected tick 3
logged and carried on: price feed hiccup
protected tick 4
protected tick 5
protected tick 6
protected tick 7
protected tick 8
after 1.5 s: ticks=8What you see: the unprotected job printed three ticks and then nothing for the remaining 1.2 seconds. isDone() was true: the schedule had ended. The exception was sitting in the ScheduledFuture, and only get() revealed it. The protected job logged the same failure on tick 3 and carried on to tick 8.
The fix is a habit, not a feature: the whole body of a scheduled task is a try/catch (Exception, and think about Error too) that logs and returns. Frameworks do this for you: Spring's @Scheduled wraps tasks in an error handler for this exact reason, though you should confirm in your version's documentation.
Bridge: thread names, one level down
A thread dump (a snapshot of every thread's stack, taken with jstack or jcmd <pid> Thread.print) lists each thread by name. In an incident you read it to find who is stuck. With default names you see pool-3-thread-7, and you must guess which of your six pools that is.
A ThreadFactory is the object a pool uses to create threads, so it is the place to set a name. Since Java 21 there is a one-liner: Thread.ofPlatform().name("notify-", 0).factory() names threads notify-0, notify-1 and so on. Before 21 you wrote a small class with an AtomicInteger.
import java.util.concurrent.*;
public class ThreadNames {
static void run(String label, ExecutorService pool) throws Exception {
for (int i = 0; i < 3; i++) pool.submit(() -> {
System.out.println(label + " -> " + Thread.currentThread().getName());
try { Thread.sleep(50); } catch (InterruptedException e) { }
});
pool.shutdown(); pool.awaitTermination(1, TimeUnit.SECONDS);
}
public static void main(String[] args) throws Exception {
run("default ", Executors.newFixedThreadPool(3));
run("named (21+) ", Executors.newFixedThreadPool(3, Thread.ofPlatform().name("notify-", 0).factory()));
ThreadFactory old = new ThreadFactory() { // the pre-21 way
private final java.util.concurrent.atomic.AtomicInteger n = new java.util.concurrent.atomic.AtomicInteger();
public Thread newThread(Runnable r) { return new Thread(r, "kitchen-" + n.incrementAndGet()); }
};
run("custom factory", Executors.newFixedThreadPool(3, old));
}
}default -> pool-1-thread-1
default -> pool-1-thread-3
default -> pool-1-thread-2
named (21+) -> notify-0
named (21+) -> notify-1
named (21+) -> notify-2
custom factory -> kitchen-1
custom factory -> kitchen-2
custom factory -> kitchen-3Idiom: name your threads
The problem: a production thread dump shows forty threads called pool-N-thread-M, and the log lines carry the same unhelpful names.
How it works: every pool takes a ThreadFactory. A name chosen there appears in thread dumps, in logs that print %t or %thread, and in profilers.
- Choose one prefix per pool, named after its job:
notify-,kitchen-,rider-io-. - Pass the factory to the constructor or to
Executors.newFixedThreadPool(n, factory). - Use the name in your first look at an incident: grep the dump for the prefix.
- Works: the run above, where the default pool printed
pool-1-thread-1and the named pools printednotify-0andkitchen-1. - Fails: names do not make threads unique across restarts, and they cost nothing, so there is no reason to skip them. For virtual threads (a later section), names are empty unless you set them; the thread-dump tool shows them differently.
- Interview takeaway: "I give every pool a ThreadFactory with a meaningful prefix, so a thread dump tells me which pool is stuck."
Bridge: the coordination toolkit, one level down
Sometimes threads must wait for each other. Before java.util.concurrent, you wrote this with wait and notify, which are easy to get wrong. Four small classes now cover nearly every case. Each one is a counter or a queue with a blocking rule. We run each in a few lines.
CountDownLatch: wait until N things have happened
A latch starts at a number. Each countDown() lowers it by one. await() blocks until it reaches zero. It cannot be reset, so it is a one-time gate. QuickBite's kitchen has three stations (grill, tandoor, dessert), and an order can be plated only when all three are ready.
import java.util.concurrent.*;
public class LatchDemo {
public static void main(String[] args) throws Exception {
CountDownLatch ready = new CountDownLatch(3); // three kitchen stations
String[] station = {"grill", "tandoor", "dessert"};
int[] prepMs = {300, 500, 200};
long t0 = System.nanoTime();
for (int i = 0; i < 3; i++) {
int k = i;
Thread.ofPlatform().name(station[k]).start(() -> {
try { Thread.sleep(prepMs[k]); } catch (InterruptedException e) { }
System.out.println(station[k] + " ready at " + ms(t0) + " ms, latch count now " + (ready.getCount() - 1));
ready.countDown();
});
}
ready.await();
System.out.println("all stations ready at " + ms(t0) + " ms -> plate the order");
}
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
}# measured on the course machine (12 cores); your numbers will differ
dessert ready at 204 ms, latch count now 2
grill ready at 304 ms, latch count now 1
tandoor ready at 504 ms, latch count now 0
all stations ready at 505 ms -> plate the orderThe plating step started at 505 ms, the moment the slowest station (tandoor, 500 ms) called countDown(). The order in which stations finish does not matter, only the count.
CyclicBarrier: everyone waits for everyone, every round
A barrier holds a group of threads until a fixed number of them have arrived, then releases all of them together, and resets for the next round. QuickBite's three riders each deliver a batch, then must meet at the hub before the next round. An optional action runs once per round when the last rider arrives.
import java.util.concurrent.*;
public class BarrierDemo {
public static void main(String[] args) throws Exception {
CyclicBarrier regroup = new CyclicBarrier(3,
() -> System.out.println(" --- all 3 riders at the hub: next round starts ---"));
long t0 = System.nanoTime();
try (ExecutorService riders = Executors.newFixedThreadPool(3)) {
for (int r = 1; r <= 3; r++) {
int id = r;
riders.submit(() -> {
for (int round = 1; round <= 2; round++) {
Thread.sleep(id * 100L); // each rider takes a different time
System.out.println("rider " + id + " back from round " + round + " at " + ms(t0) + " ms");
regroup.await(); // wait for the others
}
return null;
});
}
}
}
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
}# measured on the course machine (12 cores); your numbers will differ
rider 1 back from round 1 at 113 ms
rider 2 back from round 1 at 213 ms
rider 3 back from round 1 at 313 ms
--- all 3 riders at the hub: next round starts ---
rider 1 back from round 2 at 413 ms
rider 2 back from round 2 at 513 ms
rider 3 back from round 2 at 613 ms
--- all 3 riders at the hub: next round starts ---Rider 1 arrived at 113 ms and waited until rider 3 arrived at 313 ms. The round-two times (413, 513, 613 ms) show that nobody started round 2 before the hub meeting. Latch versus barrier in one sentence: a latch is a gate that opens once, a barrier is a meeting point that is reused.
Semaphore: at most N at the same time
A semaphore holds a number of permits. acquire() takes one and waits if none are left. release() gives one back. It limits concurrency. QuickBite's payment gateway is fragile: more than 20 calls at the same moment make it return errors. We have 100 threads that could all call it, and 400 payments to make.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class SemaphoreGateway {
static final AtomicInteger inFlight = new AtomicInteger(), maxInFlight = new AtomicInteger();
static void callPayment() throws InterruptedException { // the fragile gateway
int now = inFlight.incrementAndGet();
maxInFlight.accumulateAndGet(now, Math::max);
Thread.sleep(100);
inFlight.decrementAndGet();
}
static void run(String label, Semaphore limit) throws Exception {
inFlight.set(0); maxInFlight.set(0);
long t0 = System.nanoTime();
try (ExecutorService pool = Executors.newFixedThreadPool(100)) { // 100 threads could all call at once
for (int i = 0; i < 400; i++) pool.submit(() -> {
if (limit != null) limit.acquire();
try { callPayment(); } finally { if (limit != null) limit.release(); }
return null;
});
}
System.out.printf("%-22s 400 calls, max in flight = %3d, total %d ms%n",
label, maxInFlight.get(), (System.nanoTime() - t0) / 1_000_000);
}
public static void main(String[] args) throws Exception {
run("no limit:", null);
run("Semaphore(20):", new Semaphore(20));
}
}# measured on the course machine (12 cores); your numbers will differ
no limit: 400 calls, max in flight = 100, total 448 ms
Semaphore(20): 400 calls, max in flight = 20, total 2012 msWithout a limit, 100 calls were in flight at once and the whole batch took 448 ms. With Semaphore(20) the maximum in flight was exactly 20, and the batch took 2,012 ms. The arithmetic: 400 calls / 20 at a time = 20 waves, 20 x 100 ms = 2,000 ms. The semaphore traded speed for safety, on purpose. The pool size (100) did not need to change: the limit lives with the resource, not with the thread count. We reuse this idea with virtual threads later.
BlockingQueue: producer and consumer without wait and notify
A blocking queue is a queue where put waits when the queue is full and take waits when it is empty. A producer thread puts, a consumer thread takes, and the queue does all the waiting. A bounded queue also gives back-pressure for free. QuickBite's order thread puts tickets for the kitchen, which cooks slower than orders arrive.
import java.util.concurrent.*;
public class KitchenQueue {
record Ticket(int orderId, String dish) {}
static final Ticket CLOSED = new Ticket(-1, "poison pill");
public static void main(String[] args) throws Exception {
BlockingQueue<Ticket> queue = new ArrayBlockingQueue<>(2); // at most 2 tickets waiting
Thread producer = Thread.ofPlatform().name("orders").start(() -> {
try {
String[] dishes = {"biryani", "dosa", "pizza", "idli", "paneer tikka"};
for (int i = 1; i <= 5; i++) {
queue.put(new Ticket(i, dishes[i - 1])); // blocks when the queue is full
System.out.println("orders : put ticket " + i + " (queue size " + queue.size() + ")");
}
queue.put(CLOSED);
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = Thread.ofPlatform().name("kitchen").start(() -> {
try {
for (Ticket t; (t = queue.take()) != CLOSED; ) { // blocks when the queue is empty
Thread.sleep(150); // cooking is slower than ordering
System.out.println("kitchen : cooked " + t.dish());
}
System.out.println("kitchen : poison pill seen, going home");
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.join(); consumer.join();
}
}orders : put ticket 1 (queue size 1)
orders : put ticket 2 (queue size 1)
orders : put ticket 3 (queue size 2)
kitchen : cooked biryani
orders : put ticket 4 (queue size 2)
kitchen : cooked dosa
orders : put ticket 5 (queue size 2)
kitchen : cooked pizza
kitchen : cooked idli
kitchen : cooked paneer tikka
kitchen : poison pill seen, going homeThe queue holds at most 2 tickets. Ticket 3 went in only after the kitchen took ticket 1, and ticket 5 only after the kitchen took ticket 3: the order thread was slowed to the speed of the kitchen. The last ticket is a poison pill, a special marker object that tells the consumer to stop. Compare this with a hand-written wait and notify loop, which needs a lock, a condition check in a while loop, and care about lost signals.
| Tool | Pick it when | Cost or catch |
|---|---|---|
CountDownLatch | One thread must wait for N events, once (start gate, "all stations ready") | Cannot be reused. A missed countDown (an exception before it) hangs the waiter, so call it in finally |
CyclicBarrier | A fixed group of threads works in rounds and must sync each round | If one thread dies, the barrier breaks and the others get BrokenBarrierException |
Semaphore | Limit how many threads use a resource at once (gateway, file handles) | Release in finally. Forgetting to release leaks a permit forever |
BlockingQueue | Hand work from producers to consumers with back-pressure | Bounded queues can block producers. Unbounded queues bring back the memory trap |
wait / notify | Almost never in new code | Manual condition loops, easy to lose a signal. See E3 Q159 to Q165 |
Bridge: concurrent collections, one level down
A HashMap breaks under concurrent writes, as the revenue-report incident in section 01 showed. ConcurrentHashMap is the thread-safe map. Reads do not lock. Writes lock only the part of the table that they touch (a bin, which is a short chain of entries), so threads that write different keys do not wait for each other.
But thread-safe does not mean every sequence of calls is atomic. if (!map.containsKey(k)) map.put(k, v) is two separate calls, and another thread can run between them (a check-then-act race). Section 09 showed this with a synchronized list. ConcurrentHashMap gives you single atomic operations that replace the two-step pattern: putIfAbsent, computeIfAbsent, compute and merge.
QuickBite caches each restaurant's menu, which costs a 100 ms database query to load. Eight threads ask for "Spice Hut" at the same instant, right after a restart.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ComputeIfAbsentDemo {
static final AtomicInteger loads = new AtomicInteger();
static String loadMenu(String restaurant) { // pretend: 100 ms database query
loads.incrementAndGet();
try { Thread.sleep(100); } catch (InterruptedException e) { }
return "menu of " + restaurant;
}
static void hammer(Runnable r) throws Exception { // 8 threads ask for the same key at once
loads.set(0);
CountDownLatch go = new CountDownLatch(1);
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 8; i++) pool.submit(() -> { go.await(); r.run(); return null; });
go.countDown();
}
}
public static void main(String[] args) throws Exception {
ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();
hammer(() -> {
if (!cache.containsKey("Spice Hut")) cache.put("Spice Hut", loadMenu("Spice Hut")); // check-then-act
});
System.out.println("containsKey + put : database loads = " + loads);
cache.clear();
hammer(() -> cache.computeIfAbsent("Spice Hut", ComputeIfAbsentDemo::loadMenu));
System.out.println("computeIfAbsent : database loads = " + loads);
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++) pool.submit(() -> { for (int i = 0; i < 100_000; i++) counts.merge("orders", 1, Integer::sum); });
}
System.out.println("merge, 8 threads x 100,000 : orders = " + counts.get("orders"));
}
}containsKey + put : database loads = 8
computeIfAbsent : database loads = 1
merge, 8 threads x 100,000 : orders = 800000Idiom: computeIfAbsent instead of check-then-put
The problem: a cache does containsKey then put. All eight threads saw "absent" and all eight ran the 100 ms query. On a busy cache this multiplies database load exactly when the cache is empty.
How it works: computeIfAbsent(key, fn) checks and computes while holding the bin lock, so only one thread runs fn for a given key. The others wait briefly and receive the same value.
- Replace the check and the put with one call:
map.computeIfAbsent(key, k -> load(k)). - Keep the function short and never touch the same map inside it: it holds a lock, and an update of another key in the same map can deadlock or throw.
- For counters use
merge:map.merge(key, 1, Integer::sum)is atomic.
What you see: containsKey then put loaded 8 times. computeIfAbsent loaded exactly once. And 8 threads x 100,000 merge calls produced exactly 800,000, with no lost update. Compare this with the unsynchronized count++ race from section 08.
- Works: one load per key, correct counters, no explicit locks in your code.
- Fails: a slow function blocks other writers of the same bin, so do not do a network call that takes seconds inside it; use a map of futures (
computeIfAbsent(k, x -> CompletableFuture.supplyAsync(...))) instead.ConcurrentHashMapforbidsnullkeys and values. - Interview takeaway: "A thread-safe map still has race conditions between calls. I use computeIfAbsent and merge so the check and the update are one atomic step."
Two more concurrent collections are worth knowing by name. CopyOnWriteArrayList copies the whole array on every write, so reads are lock-free and never throw ConcurrentModificationException. It suits a list that is read constantly and changed rarely, such as a list of event listeners. ConcurrentLinkedQueue is an unbounded, lock-free queue for cases where you never need to block; if you need blocking or a bound, use a BlockingQueue.
// illustrative
List<Listener> listeners = new CopyOnWriteArrayList<>(); // read often, written rarely
listeners.add(l); // copies the array (cheap for 5 items)
for (Listener x : listeners) x.onOrder(order); // safe even if someone adds meanwhile
Queue<Event> events = new ConcurrentLinkedQueue<>(); // never blocks, never bounded| Option | Pick it when | Cost or catch |
|---|---|---|
HashMap | One thread only, or fully built before sharing and then read-only | Unsafe under concurrent writes: lost entries, wrong totals |
Collections.synchronizedMap | Quick fix on old code | One lock for everything; compound actions still race; iteration needs manual locking |
ConcurrentHashMap | Shared cache or counters with many readers and writers | Atomic per-key methods only; no null; the size is approximate under writes |
CopyOnWriteArrayList | Listener lists, small and rarely changed | Each write copies the array; terrible for big, write-heavy lists |
ConcurrentLinkedQueue | Non-blocking handoff where the size is naturally limited | No back-pressure and no blocking take |
LinkedBlockingQueue / ArrayBlockingQueue | Producer-consumer with blocking and bounds | Bounded: producers block. Unbounded: memory risk |
11 · CompletableFutureCompletableFuture: Composing Async Work
A CompletableFuture is a Future you can attach steps to. Instead of waiting for a result, you say "when it arrives, do this", and you combine several results with thenCombine and allOf. Errors travel down the chain, so every chain needs one place that handles them, and every chain that waits on slow services needs a timeout.
Back to QuickBite. The checkout endpoint calls three services: the menu (300 ms), the price (250 ms) and the rider's ETA (350 ms). The first version called them one after another and took about 900 ms. A developer was asked to make it faster and tried two rewrites. Then a third developer used CompletableFuture and shipped a bug that hung requests. We reproduce all four versions in one program.
import java.util.concurrent.*;
public class CheckoutIncident {
static String menu() { nap(300); return "menu"; }
static String price() { nap(250); return "price"; }
static String riderEta() { nap(350); return "eta"; }
static void nap(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
menu(); price(); riderEta();
System.out.println("1. one after another: " + ms(t0) + " ms");
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
t0 = System.nanoTime();
pool.submit(CheckoutIncident::menu).get(); // submit, then wait right away...
pool.submit(CheckoutIncident::price).get(); // ...so the next one starts only after
pool.submit(CheckoutIncident::riderEta).get();
System.out.println("2. 'parallel' with get() in turn: " + ms(t0) + " ms");
t0 = System.nanoTime();
Future<String> a = pool.submit(CheckoutIncident::menu);
Future<String> b = pool.submit(CheckoutIncident::price);
Future<String> c = pool.submit(CheckoutIncident::riderEta);
a.get(); b.get(); c.get(); // submit all first, wait after
System.out.println("3. submit all, then get (thread parked): " + ms(t0) + " ms");
}
// 4. the CompletableFuture version that loses its exception
CountDownLatch responseSent = new CountDownLatch(1);
CompletableFuture<String> priceCf = CompletableFuture.supplyAsync(() -> {
nap(100);
throw new IllegalStateException("price service returned 500");
});
priceCf.thenApply(p -> "total = " + p)
.thenAccept(body -> { System.out.println("sending " + body); responseSent.countDown(); });
t0 = System.nanoTime();
boolean ok = responseSent.await(1500, TimeUnit.MILLISECONDS);
System.out.println("4. response sent? " + ok + " after waiting " + ms(t0) + " ms; log lines printed by the failure: 0");
System.out.println(" the failure is only inside the future: isCompletedExceptionally=" + priceCf.isCompletedExceptionally());
}
}# measured on the course machine (12 cores); your numbers will differ
1. one after another: 900 ms
2. 'parallel' with get() in turn: 905 ms
3. submit all, then get (thread parked): 351 ms
4. response sent? false after waiting 1500 ms; log lines printed by the failure: 0
the failure is only inside the future: isCompletedExceptionally=trueWhat you see: version 1 took 900 ms: the sum. Version 2 submitted each task to a pool but called get() straight away, so the next task was not even submitted until the previous one finished: 905 ms, no gain at all. Version 3 submitted all three and then waited, and took 351 ms. That is the speed we want, but the calling thread sat parked for 351 ms. Under load that means one thread per request.
Version 4 used CompletableFuture. The price call failed. The chain was thenApply then thenAccept, with no handler. A failed future skips every step that expects a value, so nothing was sent, nothing was logged, and the client waited until its own timeout. The program printed response sent? false after waiting 1500 ms with no log line at all. The only trace is a flag inside the future that nobody reads.
The rest of this section builds, step by step, a version that is fast, handles failures and has a time limit.
Bridge: what CompletableFuture adds over Future, one level down
A plain Future has one way to get the result: ask, and wait. That is why Figure 21.15 A shows a parked thread. CompletableFuture (Java 8) keeps the same ticket idea and adds five things.
- Callbacks:
thenApply,thenAcceptand others register what to do when the result arrives. Nobody waits. - Composition: a step can start another async call (
thenCompose), so a chain can depend on earlier results. - Combination:
thenCombinejoins two futures;allOfandanyOfjoin many. - Error pipeline:
exceptionally,handleandwhenCompletedeal with failures in the chain. - Explicit completion: you can create an empty one and fill it yourself with
complete(value)orcompleteExceptionally(error). The name comes from this.
Future.get() (A) a request thread is parked all that time. With callbacks (B) it is free, and the last finishing call triggers the assembly.Future.get (blocks)
The calling thread waits at every get.
// illustrative
Future<String> m = pool.submit(menu);
Future<Integer> p = pool.submit(price);
String menu = m.get(); // parked here
int price = p.get(); // and here
return new Cart(menu, price);thenCombine (callback)
The method returns at once. The cart is built later, on whichever thread finishes last.
// illustrative
return supplyAsync(menu)
.thenCombine(supplyAsync(price),
(m, p) -> new Cart(m, p));
// a CompletableFuture<Cart> comes
// back immediately; no thread waitsThe shift: the code stops asking "give me the result" and starts saying "when the result exists, do this", so no thread is parked in between.
Bridge: the building blocks, one level down
CompletableFuture.supplyAsync(supplier) runs a Supplier on another thread and returns a future of its result. runAsync(runnable) does the same for work without a result. With no second argument they use the common pool, the shared ForkJoinPool that parallel streams also use. The first line of the output below shows its thread name.
Then the steps. thenApply(fn) transforms the value (like map). thenAccept(consumer) uses the value and returns nothing. thenRun(runnable) runs after completion and does not even receive the value.
Two steps need care. thenCompose(fn) is for a step whose function itself returns a future: "find the rider for order 7, then ask that rider's ETA". It is like flatMap: it flattens CompletableFuture<CompletableFuture<T>> into CompletableFuture<T>. thenCombine(other, fn) is for two independent futures: both start at once, and the function receives both results.
import java.util.concurrent.*;
public class CfBasics {
static String t() { return Thread.currentThread().getName(); }
static void nap(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
static long T0 = System.nanoTime();
static long ms() { return (System.nanoTime() - T0) / 1_000_000; }
record Rider(String name) {}
static CompletableFuture<Rider> riderFor(int orderId) {
return CompletableFuture.supplyAsync(() -> { nap(200); return new Rider("Kiran"); });
}
static CompletableFuture<Integer> etaFor(Rider r) {
return CompletableFuture.supplyAsync(() -> { nap(150); return 22; });
}
public static void main(String[] args) throws Exception {
// supplyAsync: runs on the common pool, caller is not blocked
CompletableFuture<String> menu = CompletableFuture.supplyAsync(() -> {
System.out.println("menu() runs on " + t()); nap(300); return "menu"; });
System.out.println("main continues at " + ms() + " ms");
// thenApply / thenAccept / thenRun
CompletableFuture<Void> chain = menu.thenApply(String::toUpperCase)
.thenAccept(m -> System.out.println("thenAccept got " + m + " at " + ms() + " ms"))
.thenRun(() -> System.out.println("thenRun: nothing passed in, at " + ms() + " ms"));
chain.join();
// thenCompose: second call NEEDS the first result
T0 = System.nanoTime();
int eta = riderFor(7).thenCompose(CfBasics::etaFor).join();
System.out.println("thenCompose: rider then ETA = " + eta + " min, took " + ms() + " ms (200 + 150)");
// thenCombine: two INDEPENDENT calls, joined when both finish
T0 = System.nanoTime();
CompletableFuture<String> m = CompletableFuture.supplyAsync(() -> { nap(300); return "menu"; });
CompletableFuture<String> p = CompletableFuture.supplyAsync(() -> { nap(250); return "price"; });
System.out.println("thenCombine: " + m.thenCombine(p, (a, b) -> a + "+" + b).join() + ", took " + ms() + " ms (max, not sum)");
// allOf / anyOf
T0 = System.nanoTime();
CompletableFuture<String> x = CompletableFuture.supplyAsync(() -> { nap(300); return "menu"; });
CompletableFuture<String> y = CompletableFuture.supplyAsync(() -> { nap(250); return "price"; });
CompletableFuture<String> z = CompletableFuture.supplyAsync(() -> { nap(350); return "eta"; });
CompletableFuture.allOf(x, y, z).join();
System.out.println("allOf: all done after " + ms() + " ms -> " + x.join() + " " + y.join() + " " + z.join());
T0 = System.nanoTime();
Object first = CompletableFuture.anyOf(
CompletableFuture.supplyAsync(() -> { nap(300); return "mirror A"; }),
CompletableFuture.supplyAsync(() -> { nap(120); return "mirror B"; })).join();
System.out.println("anyOf: first to finish = " + first + " after " + ms() + " ms");
}
}# measured on the course machine (12 cores); your numbers will differ
menu() runs on ForkJoinPool.commonPool-worker-1
main continues at 8 ms
thenAccept got MENU at 310 ms
thenRun: nothing passed in, at 314 ms
thenCompose: rider then ETA = 22 min, took 352 ms (200 + 150)
thenCombine: menu+price, took 302 ms (max, not sum)
allOf: all done after 351 ms -> menu price eta
anyOf: first to finish = mirror B after 121 msWhat you see: main continued at 8 ms while the menu was still loading, so supplyAsync did not block. The menu ran on ForkJoinPool.commonPool-worker-1. The chain printed at 310 ms (300 plus a few). thenCompose took 352 ms, which is 200 + 150: dependent calls add up. thenCombine took 302 ms, which is the maximum of 300 and 250: independent calls overlap. allOf finished after 351 ms. anyOf returned the first finisher, mirror B, after 121 ms.
A rule that falls out of those numbers: use thenCompose only when the second call needs the first result. If it does not, start both futures first and join with thenCombine. A common mistake is a long thenCompose chain of calls that did not depend on each other, which silently turns a 350 ms job into a 900 ms one.
allOf(f1, f2, f3) returns a CompletableFuture<Void>: it carries no results. After it completes, read each input with join(), which now returns instantly. anyOf returns CompletableFuture<Object> and needs a cast. Neither cancels the others when one finishes.
Bridge: which thread runs a callback, one level down
A step such as thenApply does not have its own thread. The rule has three cases, and the output shows each one.
- Not yet complete when the step is attached: the step runs on the thread that completes the future (a pool thread).
- Already complete when the step is attached: the step runs immediately on the thread that is attaching it (often
mainor a request thread). - The
*Asyncvariants (thenApplyAsync) always hand the step to an executor. Without an argument that is the common pool. With an argument it is the executor you pass.
import java.util.concurrent.*;
public class CfThreads {
static String t() { return Thread.currentThread().getName(); }
static void nap(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
public static void main(String[] args) throws Exception {
ExecutorService mine = Executors.newFixedThreadPool(2, Thread.ofPlatform().name("checkout-", 0).factory());
// Case 1: the future is NOT finished when the callback is attached
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> { nap(200); return "x"; }, mine);
slow.thenApply(v -> { System.out.println("case 1 thenApply runs on " + t()); return v; });
slow.join(); nap(50);
// Case 2: the future is ALREADY finished when the callback is attached
CompletableFuture<String> done = CompletableFuture.completedFuture("x");
done.thenApply(v -> { System.out.println("case 2 thenApply runs on " + t()); return v; });
// Case 3: *Async without an executor -> common pool; with an executor -> yours
slow.thenApplyAsync(v -> { System.out.println("case 3 thenApplyAsync runs on " + t()); return v; }).join();
slow.thenApplyAsync(v -> { System.out.println("case 4 thenApplyAsync(mine) runs on " + t()); return v; }, mine).join();
System.out.println("common pool parallelism = " + ForkJoinPool.commonPool().getParallelism());
mine.shutdown();
}
}case 1 thenApply runs on checkout-0
case 2 thenApply runs on main
case 3 thenApplyAsync runs on ForkJoinPool.commonPool-worker-1
case 4 thenApplyAsync(mine) runs on checkout-1
common pool parallelism = 11What you see: case 1 ran on checkout-0, a thread of my own pool, because the future finished later. Case 2 ran on main, because the future was already complete. Case 3 went to ForkJoinPool.commonPool-worker-1. Case 4 went to my pool again. The common pool has 11 workers here: the number of cores (12) minus one.
Why you should care: a callback that runs on the caller's thread can block the request thread, and a callback that runs on a completing thread can stall a shared pool. Rule of thumb: keep callbacks short and non-blocking, and for anything that blocks, use an *Async step with your own executor.
Idiom: give CompletableFuture its own executor
The problem: supplyAsync(() -> callRestApi()) with no executor runs a blocking call on the common pool. That pool has only 11 threads here, and parallel streams and other CompletableFuture code share it. A burst of slow calls starves everyone.
How it works: the second argument of every supplyAsync, runAsync and *Async method is an Executor. Pass a pool sized for waiting work, with a clear thread-name prefix.
- Create one executor per kind of work: an I/O pool for network calls, and keep CPU work on the common pool.
- Pass it everywhere a stage might block:
supplyAsync(task, io),thenApplyAsync(fn, io). - Size it from the downstream limit, not from the number of cores. Blocked threads use no CPU.
import java.util.*;
import java.util.concurrent.*;
public class CfOwnExecutor {
static long run(Executor ex, int n) {
long t0 = System.nanoTime();
List<CompletableFuture<String>> all = new ArrayList<>();
for (int i = 0; i < n; i++) {
all.add(CompletableFuture.supplyAsync(() -> { // 200 ms of blocking I/O
try { Thread.sleep(200); } catch (InterruptedException e) { }
return "ok";
}, ex));
}
CompletableFuture.allOf(all.toArray(new CompletableFuture[0])).join();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
System.out.println("common pool parallelism = " + ForkJoinPool.commonPool().getParallelism());
run(ForkJoinPool.commonPool(), 5); // warm-up
System.out.println("44 blocking calls on the common pool : " + run(ForkJoinPool.commonPool(), 44) + " ms");
try (ExecutorService io = Executors.newFixedThreadPool(50, Thread.ofPlatform().name("io-", 0).factory())) {
System.out.println("44 blocking calls on a 50-thread pool: " + run(io, 44) + " ms");
}
// and what a hogged common pool does to a parallel stream that needs it
System.out.println("100 items x 10 ms sleep, parallel stream, idle pool : " + stream() + " ms");
CompletableFuture<?> hog = CompletableFuture.runAsync(() -> run(ForkJoinPool.commonPool(), 44));
Thread.sleep(50); // the 44 blocking calls now hold the workers
System.out.println("100 items x 10 ms sleep, parallel stream, hogged pool: " + stream() + " ms");
hog.join();
}
static long stream() {
long t0 = System.nanoTime();
java.util.stream.IntStream.range(0, 100).parallel().forEach(i -> { try { Thread.sleep(10); } catch (InterruptedException e) { } });
return (System.nanoTime() - t0) / 1_000_000;
}
}# measured on the course machine (12 cores); your numbers will differ
common pool parallelism = 11
44 blocking calls on the common pool : 802 ms
44 blocking calls on a 50-thread pool: 211 ms
100 items x 10 ms sleep, parallel stream, idle pool : 97 ms
100 items x 10 ms sleep, parallel stream, hogged pool: 442 msWhat you see: 44 blocking calls of 200 ms each took 802 ms on the common pool, because 11 workers handle four waves (44 / 11 = 4, 4 x 200 = 800). On a pool of 50 threads they took 211 ms, one wave. And while the 44 calls held the common pool, a small parallel stream that normally took 97 ms took 442 ms: the unrelated code slowed down because it shared the pool.
- Works: blocking work is isolated and its limit is visible. Thread names show which pool is busy. Link: the same starvation affects parallel streams in section 07.
- Fails: a large executor with no limit just moves the problem to the downstream service. Put a
Semaphoreor a bounded queue in front of fragile dependencies. And never create a new executor per request: create it once and reuse it. - Interview takeaway: "The no-executor supplyAsync uses the common pool, which is for short CPU work. Anything that blocks gets its own named executor."
Bridge: errors in a chain, one level down
A CompletableFuture finishes in one of two ways: with a value, or with an exception. When a step throws, the future of that step finishes exceptionally. Every later step that expects a value (thenApply, thenCompose, thenAccept) is skipped, and the exception passes down the chain until a step that handles errors.
Three methods handle errors. They look similar and behave differently.
| Method | Runs when | Can it change the result? | Use it for |
|---|---|---|---|
exceptionally(fn) | Only on failure | Yes: returns a replacement value | A simple fallback |
handle((value, ex) -> ...) | Always | Yes: you decide from both inputs | One place that turns success or failure into a result |
whenComplete((value, ex) -> ...) | Always | No: the original result or failure continues | Logging, metrics, cleanup |
One more thing to know: an exception thrown inside a step reaches later steps wrapped in a CompletionException, and the real exception is its cause. If you call join(), it throws that CompletionException (unchecked). If you call get(), it throws an ExecutionException (checked). The cause is the same.
import java.util.concurrent.*;
public class CfErrors {
static CompletableFuture<Integer> failing() {
return CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("rider service down"); });
}
static CompletableFuture<Integer> fine() { return CompletableFuture.supplyAsync(() -> 25); }
public static void main(String[] args) throws Exception {
// exceptionally: only on failure, returns a replacement value
System.out.println("exceptionally: " + failing().exceptionally(ex -> { System.out.println(" ex type = " + ex.getClass().getSimpleName()); return -1; }).join());
// handle: always runs, gets (value, error), returns a replacement
for (CompletableFuture<Integer> f : java.util.List.of(fine(), failing()))
System.out.println("handle: " + f.handle((v, ex) -> ex == null ? v : -1).join());
// whenComplete: always runs, observes, does NOT change the result
try {
failing().whenComplete((v, ex) -> System.out.println("whenComplete saw: " + ex)).join();
} catch (CompletionException e) { System.out.println("...and the failure still reached join(): " + e.getCause()); }
// join() vs get(): same failure, different wrapper
try { failing().join(); } catch (CompletionException e) { System.out.println("join() throws " + e.getClass().getSimpleName() + " (unchecked), cause = " + e.getCause()); }
try { failing().get(); } catch (ExecutionException e) { System.out.println("get() throws " + e.getClass().getSimpleName() + " (checked), cause = " + e.getCause()); }
// the pipeline: a failure skips every thenApply and lands in the first handler
Integer r = failing().thenApply(x -> x * 2).thenApply(x -> x + 1)
.handle((v, ex) -> { System.out.println("handle after 2 skipped stages: ex = " + ex); return 30; }).join();
System.out.println("fallback ETA = " + r);
// inside a dependent stage the exception arrives wrapped in CompletionException
fine().thenApply(x -> { if (x > 0) throw new IllegalArgumentException("bad ETA " + x); return x; })
.exceptionally(ex -> { System.out.println("dependent-stage failure arrives as: " + ex); return 0; }).join();
}
} ex type = CompletionException
exceptionally: -1
handle: 25
handle: -1
whenComplete saw: java.util.concurrent.CompletionException: java.lang.IllegalStateException: rider service down
...and the failure still reached join(): java.lang.IllegalStateException: rider service down
join() throws CompletionException (unchecked), cause = java.lang.IllegalStateException: rider service down
get() throws ExecutionException (checked), cause = java.lang.IllegalStateException: rider service down
handle after 2 skipped stages: ex = java.util.concurrent.CompletionException: java.lang.IllegalStateException: rider service down
fallback ETA = 30
dependent-stage failure arrives as: java.util.concurrent.CompletionException: java.lang.IllegalArgumentException: bad ETA 25What you see: the very first line shows that even exceptionally receives a CompletionException, not the original, so use ex.getCause() when you need the real type. handle saw a value for the good future and an exception for the bad one, and returned -1 for the bad one. whenComplete saw the failure, and the failure still reached join(): it only observes. join() threw CompletionException; get() threw ExecutionException. After two skipped thenApply stages, handle still received the original failure, and the fallback 30 was returned.
One more rule for allOf: it waits for all inputs, then completes exceptionally if any failed. It does not fail fast. If you need to react to the first failure, use a structured-concurrency scope, which we meet in the next section.
Idiom: every chain ends in a handler
The problem: the version 4 chain at the start of this section: supplyAsync failed, thenApply and thenAccept were skipped, no code ran, no log line was written, and the request hung.
How it works: a failure travels to the end of the chain and stays there. Whoever owns the end of the chain must look at it.
- Decide who owns the end: the code that sends the response or returns the future to a framework.
- Add
handle(orexceptionally) as the last step to turn failure into a fallback or an error response, and log the cause. - Use
whenCompletefor logging in the middle, where it must not change the result.
// illustrative: output of this chain was: nothing, no log line
priceCf.thenApply(p -> "total = " + p)
.thenAccept(body -> send(body));// illustrative: the pattern is run for real in CheckoutFanout below
priceCf.thenApply(p -> "total = " + p)
.thenAccept(body -> send(body))
.exceptionally(ex -> {
log.error("checkout failed", ex.getCause()); // the line the incident lacked
sendError(503); // the client gets an answer now
return null;
});- Works: the client always gets an answer, and the failure shows up in the log with its cause.
- Fails: a handler placed in the middle hides errors from the end of the chain (it turns them into values). A handler that only logs and returns a fake value can turn an outage into silently wrong data.
- Interview takeaway: "A failed CompletableFuture is silent unless something reads it. I put one handle or exceptionally at the end of every chain, and I log getCause."
Bridge: timeouts, one level down
Java 9 added two methods that put a time limit on a future. orTimeout(2, SECONDS) makes the future fail with TimeoutException if it is still unfinished after 2 seconds. completeOnTimeout(fallback, 2, SECONDS) completes it with a fallback value instead. Before Java 9 you had to build this with a scheduled executor yourself.
import java.util.concurrent.*;
public class CfTimeouts {
static CompletableFuture<String> rider(int ms) {
return CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(ms); } catch (InterruptedException e) { }
return "ETA 22 min";
});
}
static long T0;
static long ms() { return (System.nanoTime() - T0) / 1_000_000; }
public static void main(String[] args) throws Exception {
T0 = System.nanoTime();
try { rider(800).orTimeout(300, TimeUnit.MILLISECONDS).join(); }
catch (CompletionException e) { System.out.println("orTimeout: " + e.getCause().getClass().getSimpleName() + " after " + ms() + " ms"); }
T0 = System.nanoTime();
System.out.println("completeOnTimeout (slow): '" + rider(800).completeOnTimeout("about 30 min", 300, TimeUnit.MILLISECONDS).join() + "' after " + ms() + " ms");
T0 = System.nanoTime();
System.out.println("completeOnTimeout (fast): '" + rider(100).completeOnTimeout("about 30 min", 300, TimeUnit.MILLISECONDS).join() + "' after " + ms() + " ms");
// the slow work is NOT cancelled by a timeout; it still runs to the end
T0 = System.nanoTime();
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(800); } catch (InterruptedException e) { }
System.out.println(" [" + ms() + " ms] the slow rider call finally finished (nobody cares)");
return "ETA 22 min";
});
String v = slow.completeOnTimeout("fallback", 300, TimeUnit.MILLISECONDS).join();
System.out.println("[" + ms() + " ms] caller got '" + v + "', work still running in the background");
Thread.sleep(700);
System.out.println("final value of that future: " + slow.join());
}
}# measured on the course machine (12 cores); your numbers will differ
orTimeout: TimeoutException after 304 ms
completeOnTimeout (slow): 'about 30 min' after 300 ms
completeOnTimeout (fast): 'ETA 22 min' after 101 ms
[301 ms] caller got 'fallback', work still running in the background
[801 ms] the slow rider call finally finished (nobody cares)
final value of that future: fallbackWhat you see: orTimeout failed with TimeoutException after 304 ms (limit 300). completeOnTimeout with a slow rider returned the fallback after 300 ms, and with a fast rider (100 ms) returned the real ETA after 101 ms. The last three lines hold the surprise: the future finished with fallback, but the slow call kept running and printed at 801 ms. A timeout does not cancel the work. It only stops waiting for it. The late result was ignored, because the future was already complete.
That has two consequences. First, a timed-out call still uses a thread and a connection until it ends, so give the HTTP client its own timeout as well. Second, the number of slow calls piling up is bounded only by your pool size, which is one more reason for a bounded pool.
Bridge: the checkout fan-out, built in five chunks
Now we assemble everything into the real checkout. The requirements are: call the menu, the price and the rider ETA at the same time on a named pool; combine them into one Checkout record; if the rider service is slow, answer with the fallback "about 30 min" after 500 ms; and if anything else fails, still answer. We build it in five chunks, then show the whole program and its output.
Chunk 1: start the three calls together. Each supplyAsync returns at once, so all three calls are in flight after three lines. The second argument is our own executor (the idiom pat-cf-own-executor).
CompletableFuture<String> menu = CompletableFuture.supplyAsync(CheckoutFanout::menu, IO);
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(CheckoutFanout::price, IO);
CompletableFuture<String> eta = CompletableFuture.supplyAsync(CheckoutFanout::riderEta, IO);Chunk 2: give only the slow call a fallback. A missing ETA is acceptable, a missing price is not. So only the ETA gets completeOnTimeout.
CompletableFuture<String> eta = CompletableFuture.supplyAsync(CheckoutFanout::riderEta, IO)
.completeOnTimeout("about 30 min", 500, TimeUnit.MILLISECONDS);Chunk 3: combine the independent results. thenCombine twice joins three futures into one record. (A small helper array carries the first two values; a nicer way is a private record.)
menu.thenCombine(price, (m, p) -> new Object[] {m, p})
.thenCombine(eta, (mp, e) -> new Checkout((String) mp[0], (Integer) mp[1], e, e.startsWith("about")))Chunk 4: a safety net and a log line. orTimeout(2, SECONDS) makes sure the whole chain finishes. whenComplete logs success or failure without changing the result.
.orTimeout(2, TimeUnit.SECONDS)
.whenComplete((c, ex) -> log(ex == null ? "assembled " + c : "FAILED: " + ex));Chunk 5: one handler at the end. The caller decides what a failure means (idiom pat-cf-handle-errors). Here a failure turns into a degraded record, but it could just as well return a 503.
checkout().handle((ok, ex) -> ok != null ? ok : new Checkout("-", 0, "unknown", true)).join();Here is the whole program. It runs three scenarios in one JVM: a normal rider (350 ms), a slow rider (800 ms) and a failing price service.
import java.util.concurrent.*;
public class CheckoutFanout {
record Checkout(String menu, int priceCents, String eta, boolean etaFallback) {}
static final ExecutorService IO =
Executors.newFixedThreadPool(8, Thread.ofPlatform().name("checkout-", 0).factory());
static long T0;
static int riderMs = 350;
static boolean priceFails = false;
static void nap(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
static long ms() { return (System.nanoTime() - T0) / 1_000_000; }
static void log(String s) { System.out.printf(" [%4d ms] %-12s %s%n", ms(), Thread.currentThread().getName(), s); }
static String menu() { nap(300); return "2 x biryani"; }
static int price() { nap(250); if (priceFails) throw new IllegalStateException("price service returned 500"); return 54700; }
static String riderEta() { nap(riderMs); return "22 min"; }
static CompletableFuture<Checkout> checkout() {
CompletableFuture<String> menu = CompletableFuture.supplyAsync(CheckoutFanout::menu, IO);
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(CheckoutFanout::price, IO);
CompletableFuture<String> eta = CompletableFuture.supplyAsync(CheckoutFanout::riderEta, IO)
.completeOnTimeout("about 30 min", 500, TimeUnit.MILLISECONDS); // only the ETA has a fallback
return menu.thenCombine(price, (m, p) -> new Object[] {m, p})
.thenCombine(eta, (mp, e) -> new Checkout((String) mp[0], (Integer) mp[1], e, e.startsWith("about")))
.orTimeout(2, TimeUnit.SECONDS) // safety net for the whole thing
.whenComplete((c, ex) -> log(ex == null ? "assembled " + c : "FAILED: " + ex));
}
static void run(String label) {
System.out.println(label);
T0 = System.nanoTime();
Checkout c = checkout()
.handle((ok, ex) -> ok != null ? ok : new Checkout("-", 0, "unknown", true)) // one place decides the fallback
.join();
System.out.println(" response after " + ms() + " ms: " + c);
}
public static void main(String[] args) {
run("normal (rider answers in 350 ms):");
riderMs = 800;
run("slow rider (800 ms): fallback at 500 ms:");
riderMs = 350; priceFails = true;
run("price service fails:");
IO.shutdown();
}
}# measured on the course machine (12 cores); your numbers will differ
normal (rider answers in 350 ms):
[ 378 ms] checkout-2 assembled Checkout[menu=2 x biryani, priceCents=54700, eta=22 min, etaFallback=false]
response after 393 ms: Checkout[menu=2 x biryani, priceCents=54700, eta=22 min, etaFallback=false]
slow rider (800 ms): fallback at 500 ms:
[ 500 ms] ForkJoinPool.commonPool-delayScheduler assembled Checkout[menu=2 x biryani, priceCents=54700, eta=about 30 min, etaFallback=true]
response after 501 ms: Checkout[menu=2 x biryani, priceCents=54700, eta=about 30 min, etaFallback=true]
price service fails:
[ 351 ms] checkout-1 FAILED: java.util.concurrent.CompletionException: java.lang.IllegalStateException: price service returned 500
response after 351 ms: Checkout[menu=-, priceCents=0, eta=unknown, etaFallback=true]What you see: in the normal run the three calls overlapped and the response took 393 ms. The 350 ms rider call is the slowest and the rest is the first run's class loading and warm-up. With the slow rider, the fallback fired at 500 ms and the response was ready at 501 ms. The 800 ms rider call was abandoned. In the third run the price service failed, the log line shows the CompletionException with its cause, and the client got an answer after 351 ms instead of hanging.
One line in the second scenario deserves attention. The fallback was assembled on a thread named ForkJoinPool.commonPool-delayScheduler. That is the single thread the JDK uses to fire timeouts. When a timeout completes a future, the dependent steps run on that thread. If those steps were slow or blocking, they would delay every other timeout in the JVM. In real code, keep the steps after a timeout short, or move them off with thenApplyAsync(fn, executor).
Idiom: fan out, fan in, with a timeout and a fallback
The problem: a request needs several independent remote results. Done in sequence it takes the sum. Done with blocking get() it ties up a thread. With no time limit one slow service holds every request.
How it works: start every call first (fan out), join them with thenCombine or allOf (fan in), cap the wait with completeOnTimeout for parts that have a safe default and with orTimeout for the whole, and end with one handler.
- Start all futures before combining any. A
thenComposechain of independent calls turns the fan-out back into a sequence. - Choose a fallback per part, or none. Only parts that can be missing get
completeOnTimeout. - Set one overall deadline shorter than the caller's own timeout, and end with
handle.
- Works: latency is the slowest required part (350 ms) or the deadline (500 ms), whichever comes first. No request thread is parked.
- Fails: abandoned calls keep running, so a slow service still receives the load. Combine this with client-side timeouts and with a limit on concurrency. Also remember that callbacks after a timeout run on the delay-scheduler thread.
- Interview takeaway: "I start all the calls first, combine with thenCombine or allOf, put a fallback on the optional part and an overall orTimeout, run it on my own executor, and end with one handle."
Two honest limits of this style. First, readability: a long chain of callbacks is harder to step through in a debugger than straight-line code, and stack traces do not show the chain. Second, you must remember every one of the rules in this section (executor, handler, timeout). The structured-concurrency API at the end of the next section aims to give the same speed with ordinary-looking code. E3's concurrency drill has more CompletableFuture interview questions at e03-java-interview-drill.html#concurrent.
| Option | Pick it when | Cost or catch |
|---|---|---|
| Sequential calls | The calls depend on each other, or latency does not matter | Time is the sum of all calls |
invokeAll on a pool | Simple batch of independent tasks; blocking is fine | Parks the caller; no per-task fallback |
CompletableFuture | Async composition, fallbacks, non-blocking callbacks | Callback style; easy to lose errors; timeouts do not cancel work |
| Virtual threads, plain code | You prefer straight-line blocking code with high concurrency (next section) | Need your own timeouts and limits |
| Structured concurrency (preview) | Fan-out where one failure should cancel the siblings | Still a preview API in Java 25 to 27 |
| Reactive libraries | Streams of events with back-pressure | A large new programming model to learn |
12 · Virtual threads and structured concurrencyVirtual Threads and Structured Concurrency
A virtual thread is a thread that costs a few kilobytes instead of a megabyte, so you can have one per task, even 100,000 at once. When it blocks on a sleep, a socket or a lock, it steps off its carrier thread and waits on the heap. They remove the need to pool threads for waiting work, but they do not make CPU work faster and they do not remove the need to limit what you send downstream.
Back to QuickBite. The partner-API gateway forwards each request to a partner restaurant's system and waits about 200 ms for the answer. It runs on a pool of 200 threads, which was sized years ago and "works fine".
On a Friday campaign, 5,000 requests arrive at the same moment. Only 200 can be served at once. The others queue for a free thread. Each wave takes 200 ms, and 5,000 / 200 = 25 waves, so the last request waits 25 x 200 ms = 5 seconds before it even starts. The p99 latency (the time that 99% of requests beat) explodes. CPU is at 3%, because every one of those 200 threads is just waiting for the network.
The old fix was a bigger pool, which costs memory per thread and runs into the operating system's limits. The new fix is to stop pooling. We measure both with 10,000 tasks that each sleep 200 ms, standing in for a network call.
Make the invisible visible: 10,000 waiting tasks on a virtual-thread-per-task executor, then on a fixed pool of 200 threads. The pool should take 10,000 / 200 x 200 ms = 10,000 ms.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class PoolVsVirtual {
static long run(ExecutorService ex, int tasks) {
AtomicInteger done = new AtomicInteger();
long t0 = System.nanoTime();
try (ex) { // close() waits for every task
for (int i = 0; i < tasks; i++)
ex.submit(() -> { Thread.sleep(200); return done.incrementAndGet(); }); // 200 ms "network call"
}
if (done.get() != tasks) throw new AssertionError();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) {
int tasks = 10_000;
System.out.println("virtual thread per task, " + tasks + " x sleep(200): " + run(Executors.newVirtualThreadPerTaskExecutor(), tasks) + " ms");
System.out.println("fixed pool of 200, " + tasks + " x sleep(200): " + run(Executors.newFixedThreadPool(200), tasks) + " ms");
System.out.println("expected for the pool: " + tasks + " / 200 x 200 ms = " + (tasks / 200 * 200) + " ms");
}
}# measured on the course machine (12 cores); your numbers will differ
virtual thread per task, 10000 x sleep(200): 259 ms
fixed pool of 200, 10000 x sleep(200): 10024 ms
expected for the pool: 10000 / 200 x 200 ms = 10000 msWhat you see: virtual threads finished 10,000 waiting tasks in 259 ms, about the length of one wait. The 200-thread pool needed 10,024 ms, which is the predicted 10 seconds. That is a 39 times difference for the same code in each task, and the only thing that changed is the executor.
Why: a pool of 200 can have 200 tasks waiting at the same time. A virtual thread that sleeps gives up its carrier thread, so 10,000 of them can wait together and the 12 carrier threads here are nearly idle.
Bridge: what a virtual thread is, one level down
A platform thread is the thread you already know. The JVM asks the operating system for a thread, which has a large fixed stack and is scheduled by the operating system. A virtual thread (final since Java 21) is a Java object that looks and behaves like a thread (it has a name, a stack, join, interrupts), but the JVM, not the operating system, schedules it.
The JVM keeps a small pool of real threads called carrier threads. By default there is one carrier per core. A virtual thread runs by being mounted on a carrier. When the virtual thread reaches a blocking call (a sleep, a socket read, a lock), the JDK unmounts it: the thread's stack is saved as an object on the heap, and the carrier immediately runs another virtual thread. When the wait ends, the scheduler mounts it again, possibly on a different carrier. Figure 21.17 draws this.
Because the stack lives on the heap and starts tiny (a few kilobytes, growing as needed), a virtual thread is cheap to create and cheap to park. You do not pool them. You create one per task and let it end.
Three ways to create one, and one way to see what you have:
// illustrative
Thread a = Thread.ofVirtual().name("order-1").start(task); // builder, started
Thread b = Thread.startVirtualThread(task); // shortcut
ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor(); // one new thread per submit
boolean v = Thread.currentThread().isVirtual(); // am I virtual?Make the invisible visible: what a virtual thread prints about itself, and how many different carriers 1,000 sleeping virtual threads actually used.
import java.util.*;
import java.util.concurrent.*;
public class VirtualBasics {
public static void main(String[] args) throws Exception {
System.out.println("cores: " + Runtime.getRuntime().availableProcessors());
Thread v1 = Thread.ofVirtual().name("order-1").start(() ->
System.out.println("inside: " + Thread.currentThread()));
v1.join();
Thread v2 = Thread.startVirtualThread(() -> System.out.println("isVirtual=" + Thread.currentThread().isVirtual()
+ ", daemon=" + Thread.currentThread().isDaemon() + ", name='" + Thread.currentThread().getName() + "'"));
v2.join();
Thread p = Thread.ofPlatform().name("notify-0").start(() -> System.out.println("platform: " + Thread.currentThread()));
p.join();
// which carriers did 1,000 sleeping virtual threads run on? (the carrier is the 'worker-N' in toString)
Set<String> carriers = ConcurrentHashMap.newKeySet();
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) ex.submit(() -> {
carriers.add(carrier());
Thread.sleep(20); // unmounts here; may resume on ANOTHER carrier
carriers.add(carrier());
return null;
});
}
System.out.println("distinct carrier threads used: " + carriers.size() + " " + new TreeSet<>(carriers));
}
static String carrier() {
String s = Thread.currentThread().toString(); // VirtualThread[#22]/runnable@ForkJoinPool-1-worker-3
return s.substring(s.indexOf('@') + 1);
}
}cores: 12
inside: VirtualThread[#26,order-1]/runnable@ForkJoinPool-1-worker-1
isVirtual=true, daemon=true, name=''
platform: Thread[#30,notify-0,5,main]
distinct carrier threads used: 12 [ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-10, ForkJoinPool-1-worker-11, ForkJoinPool-1-worker-12, ForkJoinPool-1-worker-2, ForkJoinPool-1-worker-3, ForkJoinPool-1-worker-4, ForkJoinPool-1-worker-5, ForkJoinPool-1-worker-6, ForkJoinPool-1-worker-7, ForkJoinPool-1-worker-8, ForkJoinPool-1-worker-9]What you see: the toString of a virtual thread is VirtualThread[#26,order-1]/runnable@ForkJoinPool-1-worker-1: its id and name, its state, and after the @ the carrier it is mounted on. Virtual threads are always daemon threads (they do not keep the JVM alive) and their default name is the empty string. The 1,000 sleepers used all 12 carriers, equal to the 12 cores. A platform thread prints as Thread[#30,notify-0,5,main], with a priority and a group.
Daemon status matters: if main finishes while virtual threads are still working, the JVM exits and the work is lost. That is why the examples use try (var ex = ...) or join().
Platform thread
A real OS thread with a reserved stack. A few thousand is the practical limit.
// illustrative
Thread t = new Thread(task);
t.start();
// OS thread, ~1 MB stack reserved
// scheduled by the OS
// limit: OS and memory (thousands)Virtual thread
A heap object scheduled by the JVM. Its stack grows only as needed.
// illustrative
Thread t = Thread.ofVirtual()
.start(task);
// heap object, stack in KBs
// scheduled by the JVM
// limit: heap memory (100,000s)The shift: a thread stops being a scarce operating-system resource and becomes an ordinary object, so you can have one per task instead of sharing a pool.
Creation cost, measured. The program below starts 2,000 platform threads that each sleep for a second, then 2,000 virtual threads, then 100,000 virtual threads. It keeps all of them alive at once to measure. Do not try 100,000 platform threads: on many machines that fails. We report heap use and the whole process's resident memory (RSS), because platform-thread stacks live outside the heap.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class CreateMany {
static long rssMb() throws Exception { // whole-process memory, includes thread stacks (Linux)
for (String l : java.nio.file.Files.readAllLines(java.nio.file.Path.of("/proc/self/status")))
if (l.startsWith("VmRSS:")) return Long.parseLong(l.replaceAll("\\D+", "")) / 1024;
return -1;
}
static long usedMb() { Runtime r = Runtime.getRuntime(); return (r.totalMemory() - r.freeMemory()) >> 20; }
static void batch(String label, Thread.Builder b, int n) throws Exception {
AtomicInteger running = new AtomicInteger(), peak = new AtomicInteger();
long t0 = System.nanoTime();
Thread[] ts = new Thread[n];
for (int i = 0; i < n; i++) {
ts[i] = b.unstarted(() -> {
peak.accumulateAndGet(running.incrementAndGet(), Math::max);
try { Thread.sleep(1000); } catch (InterruptedException e) { }
running.decrementAndGet();
});
ts[i].start();
}
long startedMs = (System.nanoTime() - t0) / 1_000_000;
Thread.sleep(300);
long mb = usedMb(), rss = rssMb();
for (Thread t : ts) t.join();
System.out.printf("%-26s %,7d threads: all started in %4d ms, heap %3d MB, process RSS %4d MB, peak alive %,d, total %d ms%n",
label, n, startedMs, mb, rss, peak.get(), (System.nanoTime() - t0) / 1_000_000);
}
public static void main(String[] args) throws Exception {
batch("platform threads", Thread.ofPlatform(), 2_000);
batch("virtual threads", Thread.ofVirtual(), 2_000);
batch("virtual threads", Thread.ofVirtual(), 100_000);
}
}# measured on the course machine (12 cores); your numbers will differ
platform threads 2,000 threads: all started in 157 ms, heap 13 MB, process RSS 219 MB, peak alive 2,000, total 1157 ms
virtual threads 2,000 threads: all started in 18 ms, heap 19 MB, process RSS 160 MB, peak alive 2,000, total 1019 ms
virtual threads 100,000 threads: all started in 155 ms, heap 101 MB, process RSS 242 MB, peak alive 100,000, total 1210 msWhat you see: starting 2,000 platform threads took 157 ms, and starting 2,000 virtual threads took 18 ms, about nine times less.
100,000 virtual threads, fifty times more than the platform case, were all started in 155 ms and were all alive at the same time (peak alive 100,000).
The heap grew to about 100 MB, roughly 1 KB per sleeping thread, and the process reached 242 MB in total. For comparison, 2,000 platform threads brought the process to 219 MB and 2,000 virtual threads to 160 MB. The three batches ran one after another in the same JVM, so the RSS numbers include leftovers from the earlier batches: read them as rough sizes, not exact costs. The 100,000 virtual threads fit in about the memory that 2,000 platform threads needed.
All three batches finished in about a second because they all slept one second at the same time. That is the point: waiting is parallel and cheap.
Idiom: one virtual thread per task, no pool
The problem: code that mostly waits (HTTP calls, database queries, partner APIs) runs on a fixed pool, and the pool size becomes the concurrency limit. Tasks queue even though CPU is idle.
How it works: Executors.newVirtualThreadPerTaskExecutor() starts a new virtual thread for every submitted task. There is no queue and no pool size. Closing the executor waits for all tasks.
- Use it for tasks that block, written as ordinary blocking code (
Thread.sleep, JDBC,HttpClient.send). - Do not pool the threads. Create one per task, and let it finish.
- Limit the downstream with a
Semaphore(next idiom), not with the thread count.
// illustrative: the real run is PoolVsVirtual above
try (var ex = Executors.newFixedThreadPool(200)) {
for (int i = 0; i < 10_000; i++) ex.submit(() -> callPartner());
}// illustrative: the real run is PoolVsVirtual above
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) ex.submit(() -> callPartner());
}- Works: blocking I/O with high concurrency, and the code stays simple and debuggable: the stack trace is the real call path.
- Fails: CPU-bound work gets no speed-up (measured below), and unlimited concurrency can overwhelm a database or partner. See the next two subsections.
- Interview takeaway: "Virtual threads make waiting cheap, so I create one per blocking task instead of sizing a pool. I limit downstream load with a semaphore."
Bridge: pinning, one level down
Unmounting is what makes virtual threads cheap, and sometimes the JVM cannot unmount. A virtual thread is pinned when it blocks while it cannot leave its carrier. Then the carrier thread is stuck too, and a limited number of carriers (12 here) can be blocked by 12 pinned threads.
Before Java 24 the main cause was synchronized. A virtual thread that sleeps or waits for I/O inside a synchronized block held its monitor in a way the JVM could not move, so it pinned the carrier. Java 24 (JEP 491) changed monitors so that a virtual thread can unmount while it holds one. Native frames (a call that went through native code) can still pin: for details, check the release notes.
The test is simple. We start 48 virtual threads (4 per core), and each one sleeps 200 ms inside a synchronized block on its own private lock, so there is no real lock contention. If the carriers are released, all 48 sleep at once and the batch takes about 200 ms. If every sleeper pins a carrier, only 12 can sleep at a time: 48 / 12 = 4 waves x 200 ms = 800 ms.
import java.util.concurrent.*;
public class Pin {
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
int tasks = cores * 4;
long t0 = System.nanoTime();
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < tasks; i++) {
Object lock = new Object(); // a DIFFERENT lock per task: no real contention
ex.submit(() -> {
synchronized (lock) { // blocking while holding a monitor
try { Thread.sleep(200); } catch (InterruptedException e) { }
}
});
}
}
System.out.println(System.getProperty("java.version") + ": " + tasks + " virtual threads, each sleeping 200 ms inside synchronized, on " + cores
+ " carriers -> " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
}import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
public class PinLock { // same demo, ReentrantLock instead of synchronized
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
int tasks = cores * 4;
long t0 = System.nanoTime();
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < tasks; i++) {
ReentrantLock lock = new ReentrantLock();
ex.submit(() -> {
lock.lock();
try { Thread.sleep(200); } catch (InterruptedException e) { } finally { lock.unlock(); }
});
}
}
System.out.println(System.getProperty("java.version") + ": same, with ReentrantLock -> " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
}# measured on the course machine (12 cores); your numbers will differ
25.0.5.1: 48 virtual threads, each sleeping 200 ms inside synchronized, on 12 carriers -> 221 ms
25.0.5.1: 48 virtual threads, each sleeping 200 ms inside synchronized, on 12 carriers -> 230 ms
25.0.5.1: same, with ReentrantLock -> 223 ms
21.0.13.1: 48 virtual threads, each sleeping 200 ms inside synchronized, on 12 carriers -> 819 ms
21.0.13.1: 48 virtual threads, each sleeping 200 ms inside synchronized, on 12 carriers -> 817 ms
21.0.13.1: same, with ReentrantLock -> 212 msWhat you see: on JDK 25 the synchronized version took 221 and 230 ms: the sleepers unmounted. On JDK 21 it took 819 and 817 ms, which matches the 800 ms prediction: every sleeper pinned a carrier. The ReentrantLock version took 212 ms on JDK 21, because java.util.concurrent locks always supported unmounting. That is why the old advice was "use ReentrantLock instead of synchronized in code that blocks". On Java 24 and later that advice is no longer needed for this reason.
Make the invisible visible: JDK 21 can tell you when it pins. The flag -Djdk.tracePinnedThreads=full prints a stack trace the first time a thread pins at a given place.
VirtualThread[#35]/runnable@ForkJoinPool-1-worker-12 reason:MONITOR
java.base/java.lang.VirtualThread$VThreadContinuation.onPinned(VirtualThread.java:199)
java.base/jdk.internal.vm.Continuation.onPinned0(Continuation.java:393)
java.base/java.lang.VirtualThread.parkNanos(VirtualThread.java:635)
java.base/java.lang.VirtualThread.sleepNanos(VirtualThread.java:807)
java.base/java.lang.Thread.sleep(Thread.java:507)
Pin.lambda$main$0(Pin.java:13) <== monitors:1
java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
java.base/java.lang.VirtualThread.run(VirtualThread.java:329)
21.0.13.1: 48 virtual threads, each sleeping 200 ms inside synchronized, on 12 carriers -> 812 msThe line that matters is reason:MONITOR, and the frame Pin.lambda$main$0(Pin.java:13) <== monitors:1: line 13 of the program is the sleep, and the note says one monitor is held. On JDK 25 I ran the same command with the same flag and it printed only the result line (212 ms), no trace.
That is because the property no longer exists: it was removed in JDK 24, together with JEP 491, and nothing pins on synchronized there anyway. On Java 24 and later, find the pinning that remains (native frames) with the Flight Recorder event jdk.VirtualThreadPinned instead.
Bridge: when not to use virtual threads, one level down
Virtual threads help when tasks wait. A task that computes all the time never unmounts, so it holds a carrier from start to end. The carriers are the cores, so you cannot get more than the cores can give.
import java.util.concurrent.*;
public class CpuBound {
static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) return false; return true; }
static int primesBelow(int limit) { int c = 0; for (int i = 0; i < limit; i++) if (isPrime(i)) c++; return c; }
static long run(ExecutorService ex, int tasks) throws Exception {
long t0 = System.nanoTime();
try (ex) { for (int i = 0; i < tasks; i++) ex.submit(() -> primesBelow(400_000)); }
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors(), tasks = cores * 4;
run(Executors.newFixedThreadPool(cores), cores); // warm-up
System.out.println(tasks + " CPU-bound tasks (primes below 400,000), " + cores + " cores");
System.out.println("fixed pool of " + cores + ": " + run(Executors.newFixedThreadPool(cores), tasks) + " ms");
System.out.println("virtual thread per task: " + run(Executors.newVirtualThreadPerTaskExecutor(), tasks) + " ms");
System.out.println("fixed pool of 1: " + run(Executors.newFixedThreadPool(1), tasks) + " ms");
}
}# measured on the course machine (12 cores); your numbers will differ
48 CPU-bound tasks (primes below 400,000), 12 cores
fixed pool of 12: 1055 ms
virtual thread per task: 1041 ms
fixed pool of 1: 4539 msWhat you see: 48 tasks of pure computation took 1,055 ms on a fixed pool of 12 threads and 1,041 ms on virtual threads: no gain, no loss.
A pool of 1 thread took 4,539 ms, because it used one core. That is 4.4 times slower, not 12 times: the machine was busy with other programs, so even the 12-thread runs did not get all 12 cores. For CPU-bound work, the number of workers should match the number of cores, so a fixed pool is as good as virtual threads, and a parallel stream is simpler for collections.
Three more cautions.
- Do not pool virtual threads. A pool exists to share an expensive resource. A virtual thread is cheap, and a pool of them only adds a concurrency limit and a queue back. If you want a limit, say so with a semaphore.
- Watch
ThreadLocalcaches. A habit from platform threads is to keep an expensive object per thread (a formatter, a buffer). With 100,000 virtual threads that becomes 100,000 copies. Prefer sharing immutable objects or passing values in. - Remember the downstream. Creating 10,000 threads is easy. Making 10,000 simultaneous calls to a database that accepts 50 connections is not.
Make the invisible visible: a downstream that allows at most 50 concurrent calls, hit by 1,000 virtual threads, first with no limit and then with Semaphore(50). Waiting on a semaphore is cheap for a virtual thread, since it unmounts.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class SemaphoreVirtual {
static final AtomicInteger inFlight = new AtomicInteger(), maxInFlight = new AtomicInteger();
static void callPartnerApi() throws InterruptedException { // fragile partner: 100 ms per call
maxInFlight.accumulateAndGet(inFlight.incrementAndGet(), Math::max);
Thread.sleep(100);
inFlight.decrementAndGet();
}
static long run(Semaphore limit, int tasks) {
inFlight.set(0); maxInFlight.set(0);
long t0 = System.nanoTime();
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < tasks; i++) ex.submit(() -> {
if (limit != null) limit.acquire(); // a virtual thread waiting here is cheap
try { callPartnerApi(); } finally { if (limit != null) limit.release(); }
return null;
});
}
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) {
long a = run(null, 1_000);
System.out.println("1,000 virtual threads, no limit: max in flight = " + maxInFlight + ", " + a + " ms");
long b = run(new Semaphore(50), 1_000);
System.out.println("1,000 virtual threads, Semaphore(50): max in flight = " + maxInFlight + ", " + b + " ms (1000 / 50 x 100 ms = 2000)");
}
}# measured on the course machine (12 cores); your numbers will differ
1,000 virtual threads, no limit: max in flight = 1000, 123 ms
1,000 virtual threads, Semaphore(50): max in flight = 50, 2012 ms (1000 / 50 x 100 ms = 2000)Idiom: limit concurrency with a Semaphore, not a pool size
The problem: with threads that cost nothing, concurrency is no longer limited by the pool, so nothing protects a fragile downstream. The first line above shows 1,000 calls in flight at once.
How it works: a Semaphore counts permits. A task takes one before calling the resource and gives it back after. Excess tasks wait cheaply, as unmounted virtual threads.
- Create one semaphore per limited resource, with the limit that the resource can take (50 database connections, 20 gateway calls).
- Acquire before the call, release in
finally. - Use
tryAcquire(timeout)if callers should fail fast instead of waiting indefinitely.
// illustrative: the full program is SemaphoreVirtual above
static final Semaphore PARTNER = new Semaphore(50);
static String callPartner() throws InterruptedException {
PARTNER.acquire(); // waits here if 50 calls are already running
try {
return httpClient.send(request, ofString()).body();
} finally {
PARTNER.release(); // always give the permit back
}
}What you see: without a limit, the maximum in flight was 1,000, and the batch took 123 ms. With Semaphore(50) the maximum in flight was exactly 50, and the batch took 2,012 ms: 1,000 calls / 50 at a time = 20 waves x 100 ms = 2,000 ms. The same shape as the payment-gateway semaphore earlier in this section, but now the waiting threads cost almost nothing.
- Works: the downstream sees a steady 50, no matter how many tasks exist. The limit is explicit in the code, named, and easy to change.
- Fails: a semaphore is per JVM, so ten instances still allow 500 calls in total. For a global limit you need a shared mechanism such as a rate limiter at the gateway. Forgetting
finallyleaks permits until everything blocks. - Interview takeaway: "Virtual threads remove the thread count as an accidental limit, so I add the limit on purpose, with a Semaphore sized to what the downstream can take."
Bridge: scoped values, one level down
A request often carries a small piece of context, such as a request id or the logged-in user, that many layers need: controller, service, repository, logger. Passing it as a parameter through every method is noisy. The classic shortcut is a ThreadLocal: a variable with a separate value for each thread.
ThreadLocal has three problems. It is mutable, so any code can change it. It lives until someone calls remove(), and forgotten removals leak data between requests on pooled threads. And with millions of virtual threads, per-thread storage multiplies.
A scoped value (ScopedValue, final in Java 25, JEP 506) fixes those. You bind a value for the duration of one call, anything called inside can read it, and when the call ends the binding disappears by itself. The value cannot be reassigned inside the scope. A nested where creates a new binding for the inner scope only.
import java.util.concurrent.*;
public class ScopedValueDemo {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static final ThreadLocal<String> TL = new ThreadLocal<>();
static void controller() { service(); }
static void service() { repository(); }
static void repository() { System.out.println(" repository sees request id: " + (REQUEST_ID.isBound() ? REQUEST_ID.get() : "(not bound)")); }
public static void main(String[] args) throws Exception {
System.out.println("outside any scope: bound? " + REQUEST_ID.isBound());
ScopedValue.where(REQUEST_ID, "req-42").run(() -> {
System.out.println("inside the scope:");
controller();
ScopedValue.where(REQUEST_ID, "req-43").run(() -> { // rebinding is nested, not overwriting
System.out.println("nested rebinding:");
controller();
});
System.out.println("back in the outer scope:");
controller();
});
System.out.println("after the scope: bound? " + REQUEST_ID.isBound());
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) { // one request per virtual thread
for (int i = 1; i <= 3; i++) {
String id = "req-" + (100 + i);
ex.submit(() -> ScopedValue.where(REQUEST_ID, id).run(ScopedValueDemo::repository));
}
}
// ThreadLocal: set stays until somebody removes it
TL.set("req-42");
System.out.println("ThreadLocal is still set after the work is over: " + TL.get() + " (you must remove() it)");
}
}outside any scope: bound? false
inside the scope:
repository sees request id: req-42
nested rebinding:
repository sees request id: req-43
back in the outer scope:
repository sees request id: req-42
after the scope: bound? false
repository sees request id: req-103
repository sees request id: req-101
repository sees request id: req-102
ThreadLocal is still set after the work is over: req-42 (you must remove() it)What you see: outside the scope the value was not bound. Inside where(REQUEST_ID, "req-42").run(...), three method levels down, the repository saw req-42 without any parameter being passed. The nested binding showed req-43 inside and the outer req-42 came back after it. After the scope the value was unbound again. Three virtual threads each saw their own id (the print order differs, as threads race). The last line shows the ThreadLocal contrast: its value is still there after the work is over, until someone removes it.
Scoped values were incubating in Java 20, a preview from 21, and final in 25. If your code must also run on 21, you will still need ThreadLocal there. Compare the API on your own version with the Javadoc.
Bridge: structured concurrency, one level down
Look back at the checkout with CompletableFuture. When the price call fails, the menu and ETA calls keep running, and nobody tells them to stop. Their results are thrown away, but they still use threads and connections. The code does not show that the three calls belong together.
Structured concurrency is the idea that concurrent subtasks should live inside a block, like local variables do. The block ends only when all its subtasks have ended. If one fails, the others are cancelled. The code's shape (a try-with-resources block) matches the tasks' lifetime. In the JDK this is StructuredTaskScope. In Java 25 it is a preview API, so you must compile and run with --enable-preview. First, what happens without the flag.
StructuredDemo.java:2: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope.Subtask;
^
(use --enable-preview to enable preview APIs)
StructuredDemo.java:2: error: Subtask is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope.Subtask;
^
(use --enable-preview to enable preview APIs)The compiler refuses with this message:
StructuredTaskScope is a preview API and is disabled by defaultThis is the safety catch: a preview feature cannot slip into a build by accident. Now with the flag. The program forks the menu, price and rider calls inside one scope, joins, and builds the record. In the second scenario the price call fails.
import java.util.concurrent.*;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class StructuredDemo {
record Checkout(String menu, int priceCents, String eta) {}
static long T0;
static long ms() { return (System.nanoTime() - T0) / 1_000_000; }
static void nap(int ms) throws InterruptedException { Thread.sleep(ms); }
static Checkout checkout(boolean priceFails) throws Exception {
try (var scope = StructuredTaskScope.open()) { // default: all must succeed
Subtask<String> menu = scope.fork(() -> { nap(300); return "2 x biryani"; });
Subtask<Integer> price = scope.fork(() -> {
nap(250);
if (priceFails) throw new IllegalStateException("price service returned 500");
return 54700;
});
Subtask<String> eta = scope.fork(() -> {
try { nap(350); return "22 min"; }
catch (InterruptedException e) { System.out.println(" [" + ms() + " ms] rider call cancelled (interrupted)"); throw e; }
});
scope.join(); // waits; throws if any failed
return new Checkout(menu.get(), price.get(), eta.get());
}
}
public static void main(String[] args) throws Exception {
T0 = System.nanoTime();
System.out.println("all succeed -> " + checkout(false) + " after " + ms() + " ms");
T0 = System.nanoTime();
try {
checkout(true);
} catch (StructuredTaskScope.FailedException e) {
System.out.println("one fails -> " + e.getClass().getSimpleName() + " after " + ms() + " ms, cause: " + e.getCause());
}
}
}all succeed -> Checkout[menu=2 x biryani, priceCents=54700, eta=22 min] after 365 ms
[253 ms] rider call cancelled (interrupted)
one fails -> FailedException after 254 ms, cause: java.lang.IllegalStateException: price service returned 500What you see: with all three calls succeeding, the checkout was ready after 365 ms. When the price call failed at 250 ms, the scope was shut down at once: the rider call, which would have run until 350 ms, was interrupted at 253 ms and the exception reached the caller as FailedException with the real cause, after 254 ms. No handler had to be remembered, nothing hung, and no work was left running.
The code reads top to bottom like ordinary blocking code, which is the point. The three fork calls run each task in its own virtual thread, join() waits for all (or for the first failure), and get() on each Subtask is safe after join. Compare it with the five chunks of the CompletableFuture version.
Why is it still a preview? The API has been redesigned between previews. In Java 21 to 24 you chose behaviour by creating ShutdownOnFailure or ShutdownOnSuccess. In the Java 25 preview, a single StructuredTaskScope.open() takes an optional policy (a "joiner"), and the result of join changed (I read this in the release notes; check them before relying on the details).
It is a preview again in 26 and 27, so expect more refinement. Rule: use it in experiments, tests and internal tools if your team accepts the flag. Do not ship it as a dependency of a library that must run without preview features.
The scoped values from the previous subsection fit here: values bound before a scope are visible inside the forked subtasks, which is the main reason the two APIs were designed together.
Bridge: the decision tree, one level down
This section and the earlier ones gave you eight tools. Beginners often ask "which one do I use?", and the answer depends on the shape of the work, not on which tool is newest. Work through Figure 21.18 from the top and stop at the first question you can answer "yes".
Some notes on the order. Questions 1 and 2 are about correctness: if threads share a counter or must change several fields together, no choice of pool will fix a race, and you need atomics or a lock (section 09).
Questions 3 and 4 are about CPU-bound work: a parallel stream is the simplest for a collection, and a fixed pool of about one thread per core is right for separate tasks. Question 5 is about work that waits, where virtual threads shine. Question 6 is about composing results of async calls: CompletableFuture now, structured concurrency once it is final.
| Tool | Pick it when | Cost or catch |
|---|---|---|
| Parallel stream | Big collection, CPU work per element, no shared state, measured faster | Common pool shared with the whole JVM; bad for blocking |
| Fixed pool of ~cores | Separate CPU-bound jobs, such as image or report generation | You size it; a bounded queue and a rejection policy are on you |
| Virtual threads | Many tasks that wait on network or disk | No help for CPU work; limit the downstream; pinning on native frames |
CompletableFuture | Compose several async results with fallbacks and deadlines | Callback style, error handling is manual, timeouts do not cancel |
| Structured concurrency | Fan-out where a failure should cancel siblings | Preview in 25 to 27; needs --enable-preview |
Atomics, LongAdder | One shared counter or flag | Single variable only |
| Locks | Several fields must stay consistent together | Deadlock risk; hold them briefly |
Where to go next. The threads and locks that all of these build on are in sections 08 and 09. For the JVM internals of virtual threads (continuations, the scheduler, the memory model), read Chapter E2's Loom section and the Java Memory Model section. For interview-level questions on pools, futures and locks, use E3's concurrency drill. The drill in this chapter, Q61 to Q100, covers the same ground from zero.
13 · DrillJava Features by Version — Q1–Q25
The first twenty-five questions are about the language and library itself: which release gave you what, what each feature replaced, and how to upgrade without breaking things. Interviewers use these to find out whether you write Java 8 with a newer compiler or really use what the JDK has shipped since. Every feature here also has a card in section 02 (Java 8 to 17) or section 03 (Java 18 to 27).
The answers lean on one habit: a claim about a version is proved by compiling the same file with javac --release N-1 (it fails) and javac --release N (it works). The error lines are pasted from the course machine, which runs JDK 25.0.5; older JDKs 8, 17 and 21 were also used where a run, not just a compile, was needed.
Programs and outputs are saved in code/e21-modern-java/E/. Java 26 and 27 could not be run here, so what is said about them comes from the release notes and is marked as such.
These ten questions test whether you can place each big feature on the release timeline and say what it replaced, instead of listing keywords.
Q1. "Walk me through the LTS releases since Java 8 and the one feature from each that changed how you write code."
Reveal answer
The real test Whether you know what LTS means (a release the vendors keep patching for years) and can name one concrete habit change per release, not a feature list.
Strong answer LTS stands for long-term support. Oracle and the other vendors publish a new Java every six months, but only some releases get security fixes for many years. Companies run production on those. Since Java 8 the LTS releases are 8, 11, 17, 21 and 25, and the next one is 29 in September 2027.
Java 8 (2014): lambdas and streams. You stopped writing loops and anonymous classes for simple data work. Java 11 (2018): a standard HttpClient, String.isBlank/strip/repeat/lines, and running a single file with java Hello.java. It is the release where "just use the JDK" became realistic for small tools.
Java 17 (2021): the bundle of "less boilerplate" features that arrived across 14 to 17: records, switch expressions, text blocks, pattern matching for instanceof and sealed classes. This is the release that changes how you model data.
Java 21 (2023): virtual threads (cheap threads for blocking code), pattern matching in switch, record patterns and sequenced collections (getFirst, getLast, reversed). Java 25 (2025): scoped values, flexible constructor bodies, import module, compact source files, and stream gatherers (final since 24).
The honest summary: 8 changed how you handle data, 17 changed how you define data, 21 changed how you handle waiting, and 25 removes the last ceremony.
Picture it The same compiled class file, run on four JDKs, shows the LTS promise: old code keeps running on every newer LTS. Only the other direction (new code on an old JDK) fails.
The setup: One tiny class prints the Java version it runs on. It is compiled once with --release 8, and the single resulting class file is launched on JDK 8, 17, 21 and 25. JDK 11 is not installed on the course machine, so it is skipped.
public class Q01_Hello {
public static void main(String[] args) {
System.out.println("running on Java " + System.getProperty("java.specification.version")
+ " (" + System.getProperty("java.vm.name") + ")");
}
}Make the invisible visible: Run the one class file on each JDK.
$ javac --release 8 Q01_Hello.java # one class file, compiled once
warning: [options] source value 8 is obsolete and will be removed in a future release
warning: [options] target value 8 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
3 warnings
$ java-8 Q01_Hello
running on Java 1.8 (OpenJDK 64-Bit Server VM)
$ java-17 Q01_Hello
running on Java 17 (OpenJDK 64-Bit Server VM)
$ java-21 Q01_Hello
running on Java 21 (OpenJDK 64-Bit Server VM)
$ java (JDK 25) Q01_Hello
running on Java 25 (OpenJDK 64-Bit Server VM)What you see: The same bytes ran on 8, 17, 21 and 25 and each reported its own version. The three warning lines at the top come from the compiler, which calls --release 8 obsolete.
Why: Backward compatibility is why LTS upgrades are mostly safe: an old jar does not need recompiling. The risk sits in the things the new JDK removed or locked down, which is why questions 21 to 23 exist.
| LTS | Year | The habit it changed | Card |
|---|---|---|---|
| 8 | 2014 | Pass behaviour as lambdas, process data with streams | v8 |
| 11 | 2018 | Use the built-in HttpClient and the new String methods | v11 |
| 17 | 2021 | Model data with records and sealed types | v17 |
| 21 | 2023 | Block freely on virtual threads, match patterns in switch | v21 |
| 25 | 2025 | Scoped values, compact files, flexible constructors | v25 |
Land it I answer with the one habit each LTS changed: 8 data handling, 17 data definition, 21 blocking code, 25 less ceremony.
- "Why not just stay on the newest non-LTS release?"
-
You can, but you pay for it. A non-LTS release such as 22 or 26 is supported for only six months, until the next release arrives. After that it gets no security fixes, so you must upgrade again within half a year.
For a team with a service in production that is too fast. Each upgrade means rebuilding, running the test suite, checking that frameworks such as Spring support the new version, and rolling out. Doing that twice a year is real work for almost no extra benefit.
Non-LTS releases are useful in two places. Library authors test against them so they find breakage early. Teams that want a feature (say, gatherers in Java 24) can adopt it when it is final instead of waiting for 25.
My default is the latest LTS. I skim the non-LTS release notes twice a year so that the LTS upgrade holds no surprise.
- "How long is an LTS actually supported?"
-
It depends on the vendor, and the numbers change, so check the vendor page before a planning meeting. As a rough guide, free updates from the major OpenJDK builds (Temurin, Corretto, Zulu, Microsoft) usually run several years per LTS, and paid support from Oracle and others runs longer, often a decade in total for the oldest LTS releases.
The cadence matters more than the exact dates. A new LTS arrives every two years (17, 21, 25, then 29 in September 2027). Planning to jump from one LTS to the next, roughly every two to four years, keeps you inside support without chasing every release.
One practical point: Java 8 is still patched by several vendors, which is why many companies are still on it. "Still patched" does not mean "still pleasant". New libraries drop Java 8 support, and you miss records, virtual threads and everything else in this chapter.
When a manager asks "can we wait", I answer with the library side: the frameworks we depend on set the real deadline.
- "Is Java 11 worth stopping at, or should I jump straight from 8 to 17?"
-
Jump to 17 if you can, and treat 11 as a stepping stone only if the jump is too big. The painful part of leaving Java 8 is not the new syntax. It is the removals and the stricter rules that arrived on the way: the Java EE modules (JAXB, JAX-WS) were removed in 11, and reflection into JDK internals was locked down by 16 and 17.
Those problems exist whether you stop at 11 or not. By going straight to 17 you pay them once, and you get the 12 to 17 features immediately. By stopping at 11 you pay them in two steps and only get
varand the HttpClient.The exception is a very large application with old frameworks. There an intermediate build on 11 is a safe checkpoint: you fix the removed modules first, deploy, then handle the encapsulation problems for 17.
Whatever route you take, compile with
--releaseset to the target, run the tests on the new JDK, and read the warnings. Question 22 shows the biggest start-up failure in detail. - "What does a six-month release actually contain if almost nothing is final?"
-
Most of each release is internal: faster garbage collectors, start-up improvements, security updates and bug fixes. Small library additions arrive final, such as
Math.clampin 21 orString.indentin 12. The visible language changes arrive in preview first, which means "here is the design, try it, tell us what is wrong" (question 19).That is why a feature often takes two or three releases to become final. Switch expressions were preview in 12 and 13 and final in 14. Records were preview in 14 and 15 and final in 16. Virtual threads were preview in 19 and 20 and final in 21.
It also explains the shape of the cadence. An LTS is a snapshot of whatever became final in the previous two years. Java 17 collects what was finished from 12 to 17, and Java 21 collects what was finished from 18 to 21.
So reading release notes for 18, 19 and 20 matters less than reading the LTS notes. I skim the in-between ones for previews I might want to try.
Q2. "Why was Java 8 the biggest release in a decade? Name what it added and what each replaced."
Reveal answer
Strong answer Java 8 changed the language itself, not only the libraries. Before it, passing behaviour to a method meant writing a whole anonymous class. After it, you write the behaviour in one line. Everything else in the release builds on that.
The additions, each with the thing it replaced:
- Lambdas and method references replaced anonymous inner classes for one-method interfaces:
(a, b) -> a.length() - b.length()instead of six lines. - Stream API replaced hand-written loops for filter, transform and total: you describe the result, not the steps.
- Default and static interface methods let the JDK add methods such as
forEachandComparator.comparingto old interfaces without breaking every implementer. Optionalreplaced returningnullto mean "nothing here".java.timereplacedDateandCalendar, which were mutable and confusing.CompletableFuturereplaced hand-written callbacks for async chains, and newMapmethods (merge,computeIfAbsent,getOrDefault) replaced get-check-put code.
It also moved PermGen to Metaspace and added LongAdder and StampedLock for concurrency. Interviewers like this answer when it ends on "and it made functional-style code idiomatic in a language that had none".
Picture it One small program uses six of those features. It was compiled and run on a real JDK 8, so it shows the features existed there.
The setup: The program sorts by length with a lambda, filters and joins with a stream, handles absence with Optional, adds days with java.time, calls a default method and merges counts into a map. It is compiled with JDK 8's own javac.
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
public class Q02_Java8 {
interface Greeter { String name(); default String hello() { return "hello " + name(); } }
public static void main(String[] args) {
List<String> items = Arrays.asList("biryani", "raita", "dosa", "idli");
Collections.sort(items, (a, b) -> a.length() - b.length()); // lambda
System.out.println(items);
System.out.println(items.stream().filter(s -> s.length() > 4) // Stream API
.map(String::toUpperCase).collect(Collectors.joining(", ")));
Optional<String> first = items.stream().filter(s -> s.startsWith("z")).findFirst();
System.out.println("Optional: " + first.orElse("none")); // Optional
System.out.println(LocalDate.of(2026, 11, 28).plusDays(3)); // java.time
Greeter g = () -> "asha"; // default method
System.out.println(g.hello());
Map<String, Integer> m = new HashMap<>();
m.merge("biryani", 1, Integer::sum); m.merge("biryani", 1, Integer::sum);
System.out.println(m); // Map.merge
}
}Make the invisible visible: Compile and run on JDK 8.
$ javac -version # JDK 8
javac 1.8.0_514
$ java Q02_Java8 # JDK 8
[dosa, idli, raita, biryani]
RAITA, BIRYANI
Optional: none
2026-12-01
hello asha
{biryani=2}What you see: Every feature worked on a real Java 8: the lambda sorted the list, the stream joined two names, Optional gave "none", plusDays(3) moved the date, and merge counted two biryani orders.
Why: Nothing here needs a library or a framework. Every line compiles on a plain JDK 8, so there was no excuse after 2014 for anonymous classes and manual loops, and many codebases still carry them.
Java 7
Six lines for one comparison.
Collections.sort(items,
new Comparator<String>() {
public int compare(String a, String b) {
return a.length() - b.length();
}
});Java 8
One line, same meaning.
items.sort(
(a, b) -> a.length() - b.length());
// or, even shorter
items.sort(Comparator.comparingInt(
String::length));The shift: A lambda is the body of the single abstract method, without the class wrapper around it.
Land it I say Java 8 made functions values: lambdas, streams, Optional and the new interface methods all follow from that one change.
- "Is a lambda just syntax sugar for an anonymous class?"
-
No. It reads like sugar, but the compiler and the JVM treat it differently. An anonymous class is compiled to its own
.classfile (Outer$1.class) and loaded like any other class. A lambda body is compiled into a private method of the enclosing class, and the JVM builds the object at run time usinginvokedynamic, a special instruction added in Java 7 for this purpose.Two visible differences follow. Inside a lambda,
thismeans the enclosing object, because the lambda has no identity of its own. Inside an anonymous class,thisis the anonymous object. And a lambda does not create a class file you can see on disk.The practical result is that lambdas start faster in large numbers and the JVM can later change how it builds them without recompiling your code.
I still call it "syntax sugar" in conversation only to mean "same effect for the reader". In an interview I give the invokedynamic answer, because it shows I know what the compiler really does.
- "What were the downsides or traps of Java 8 features that people hit?"
-
Four come up again and again. First, streams used for everything: a four-step loop turned into a nine-line pipeline is not always clearer, and debugging a stream is harder than debugging a loop.
Second, parallel streams used without measuring. They share one global thread pool, and blocking work inside them can slow unrelated code, as question 57 shows with numbers.
Third,
Optionalused as a field or parameter type. It was designed for return values only. As a field it adds an object per value, cannot be serialised by default, and invitesnullto hide inside it anyway.Fourth, default methods hide diamond problems: if two interfaces give the same default method to one class, the class must pick one explicitly or it will not compile.
None of these are reasons to avoid the features. They are reasons to know the rule of thumb for each: streams for data pipelines, parallel only after measuring, Optional only for returns, and explicit overrides when interfaces collide.
- "What did Java 8 not fix that later versions did?"
-
Mostly verbosity and data modelling. Java 8 still needed forty lines for a class that only holds data (constructor, getters,
equals,hashCode,toString). Records in Java 16 reduced that to one line.It still had no multi-line strings, so JSON or SQL in code meant quote-and-plus. Text blocks in Java 15 fixed that. Its
switchwas a statement that fell through by default; switch expressions in Java 14 fixed that.It had no way to say "this interface has exactly these implementations", so the compiler could not check a
switchfor completeness. Sealed classes (17) and pattern matching (21) fixed that.And it still gave you a thread per blocking call, which limited how many requests a server could hold at once. Virtual threads (21) addressed that.
So the line I use is: Java 8 gave us functions, Java 14 to 17 gave us data, Java 21 gave us cheap waiting. The sections that follow in this chapter walk those steps in order.
- "Why were default methods needed, and what happens when two defaults collide?"
-
The JDK wanted to add methods such as
List.sort,Collection.streamandIterable.forEach. Before Java 8, adding a method to an interface broke every class that implemented it, because each one would suddenly be missing it. A default method carries a body inside the interface, so old implementers inherit it and keep compiling.If a class implements two interfaces that both define a default method with the same signature, the compiler refuses until you decide. You write the method in the class and say which one you mean, for example
A.super.hello().The rules, in order: a method in the class or a superclass wins over any interface default. Otherwise a more specific interface wins over a less specific one. Otherwise you must override explicitly.
Use defaults for evolving an API, not for storing state or building a second inheritance tree. An interface still cannot hold fields, which is the line that keeps the feature safe.
Q3. "What is var (Java 10), and where is it a bad idea?"
Reveal answer
Strong answer var lets the compiler work out the type of a local variable from the value on the right. var total = 0L; is a long, and var orders = new ArrayList<String>(); is an ArrayList<String>. The type is still fixed at compile time. var is not dynamic typing.
It works only for local variables with an initialiser: inside methods, in for loops and in try-with-resources. It does not work for fields, method parameters or return types. In Java 11 it was extended to lambda parameters, which is useful when you need to add an annotation.
It is a good idea when the type is already obvious from the right side, or very long: var entries = map.entrySet(); and for (var e : map.entrySet()). It removes repetition without removing information.
It is a bad idea when the right side hides the type. var data = service.load(); tells the reader nothing. var list = new ArrayList<>(); infers ArrayList<Object>, rarely what you meant. Numeric literals are a trap too: var x = 1; is an int, and you may have wanted long.
A rule I use: if a reviewer has to hover the mouse over the variable to learn its type, spell the type out.
Picture it Four lines show what var infers, and one list shows the diamond trap. Then a second file shows the five lines the compiler refuses.
The setup: Q03_Var.java uses var four ways. It first goes through javac --release 9 (fails) and --release 10 (works).
import java.util.*;
public class Q03_Var {
public static void main(String[] args) {
var orders = new ArrayList<String>(); // ArrayList<String>
var total = 0L; // long
var name = "asha"; // String
var oops = new ArrayList<>(); // ArrayList<Object>, not what you meant
orders.add("biryani");
System.out.println(orders.getClass().getSimpleName() + " " + total + " " + name);
oops.add(42); oops.add("text");
System.out.println("oops holds: " + oops);
for (var e : Map.of("k", 1).entrySet()) System.out.println(e.getKey() + "=" + e.getValue());
}
}Make the invisible visible: Compile proof, then the run.
$ javac --release 9 Q03_Var.java
Q03_Var.java:5: error: cannot find symbol
var orders = new ArrayList<String>(); // ArrayList<String>
^
symbol: class var
location: class Q03_Var
Q03_Var.java:6: error: cannot find symbol
var total = 0L; // long
^
symbol: class var
location: class Q03_Var
... (3 more errors trimmed)
$ javac --release 10 Q03_Var.java
(compiles)
ArrayList 0 asha
oops holds: [42, text]
k=1What you see: On release 9 the compiler looks for a class called var and cannot find it. On release 10 it compiles. The trap shows in the output: oops holds: [42, text] is an ArrayList<Object> that accepts anything.
Make the invisible visible: The cases where var must be refused, so the compiler protects you.
$ javac --release 25 Q03_VarBad.java
Q03_VarBad.java:6: error: cannot infer type for local variable a
var a; // no initializer
^
(cannot use 'var' on variable without initializer)
Q03_VarBad.java:7: error: cannot infer type for local variable b
var b = null; // no type to infer
^
(variable initializer is 'null')
Q03_VarBad.java:8: error: cannot infer type for local variable c
var c = () -> 1; // lambda needs a target type
^
(lambda expression needs an explicit target-type)
Q03_VarBad.java:9: error: cannot infer type for local variable d
var d = {1, 2}; // array initializer needs a type
^
(array initializer needs an explicit target-type)
Q03_VarBad.java:11: error: incompatible types: String cannot be converted to int
n = "text"; // n is int, forever
^Why: var needs a type it can see. With null, a lambda, an array initialiser or no initialiser, there is nothing to infer from, so the compiler says so. And var n = 1; followed by n = "text"; fails because n is an int forever.
Spelled out
The type is written twice.
Map<String, List<Order>> byCity =
new HashMap<String, List<Order>>();
for (Map.Entry<String, List<Order>> e
: byCity.entrySet()) {
List<Order> list = e.getValue();
}With var
Written once, still static.
var byCity =
new HashMap<String, List<Order>>();
for (var e : byCity.entrySet()) {
var list = e.getValue();
}
// not here: var data = service.load();The shift: The right side already says the type, so repeating it on the left adds noise, not safety.
Land it I use var when the right-hand side shows the type and avoid it when a reader would have to guess.
- "Is var the same as dynamic typing or Object?"
-
No. A
varvariable has one exact type, chosen when the file is compiled, and it can never change. The IDE shows it, the compiler checks every use of it, and the bytecode is identical to what you would get by writing the type out.The confusion comes from languages like JavaScript or Python, where a variable can hold a number now and a string later. In Java,
var n = 1; n = "text";fails to compile (see the second output above) becausenis anint.It is also not
Object.var s = "hello";lets you calls.length()becausesis aString. If it wereObject, that call would not compile.There is one subtle case. With anonymous classes,
varkeeps the anonymous type, so you can call methods that exist only on it. That is rare in real code, but it is a real difference from declaring the variable as the interface. - "Can you use var for fields, parameters or return types?"
-
No, and the restriction is deliberate. A local variable lives in a few lines, so the reader can see how it was created. A field, parameter or return type is part of a class's public shape. Other files and other teams read it without seeing the initialiser, so the type must be written down.
Inferring those types would also make a method signature depend on its body. Changing one line inside a method could silently change the type that every caller sees, and the compiler could not report the change as a mistake.
The allowed places are local variables with initialisers, enhanced and classic
forvariables, try-with-resources variables, and (since 11) lambda parameters, where it is mainly useful for attaching an annotation like@Nonnullwithout writing the type.If you need a long type in a field, use a type alias in your head: a small named class or record is usually a better answer than inferring anything.
- "What does var do with generics and the diamond?"
-
It infers from the right side only, so the diamond
<>has nothing to look at.var list = new ArrayList<>();becomesArrayList<Object>, and the earlier output shows it happily accepting both anIntegerand aString.The fix is to put the type argument on the right:
var list = new ArrayList<String>();. Or, if the type should be an interface, do not usevarat all:List<String> list = new ArrayList<>();. That also lets you swap the implementation later.That second point matters. With
var, the variable gets the exact class on the right (ArrayList), not the interface (List). Methods that exist only onArrayList, such asensureCapacity, become callable, and a later change of implementation can break callers.For anything that crosses a method boundary I declare the interface type.
varstays inside a method body. - "Is var a keyword? Can I still have a variable or method called var?"
-
It is a reserved type name, not a full keyword. You can still name a variable or a method
var, and the earlier output of the next scenario (question 21) does exactly that withint var = 5;. What you cannot do, from Java 10 on, is name a class, interface or type parametervar.That is deliberate. Making it a full keyword would have broken thousands of programs that used
varas a variable name. Making it a type name was a compromise that broke only the very few programs with a class calledvar.The same trick was used for later words:
record,sealed,permitsandyieldare contextual. They are special only in the position where the grammar expects them.The practical advice is to avoid the name anyway. A variable called
varcompiles and confuses everyone.
Q4. "Switch expressions (Java 14) versus the old switch statement — what problems do they fix?"
Reveal answer
Strong answer The old switch was a statement with three habits that caused bugs. It fell through: without a break after a case, execution continued into the next case. It could not return a value, so you assigned a variable in every branch. And it was not checked for completeness: adding an enum constant gave no warning anywhere.
A switch expression, final in Java 14, fixes all three. The arrow form case X -> value; never falls through. The whole switch is an expression, so return switch (s) { ... }; works. And when the selector is an enum or a sealed type, the compiler checks that every case is covered.
You can list several labels in one case (case SAT, SUN -> "weekend"). When a branch needs several statements, use a block and yield the result. There is no default needed if all constants are covered, and that is a feature: adding a constant later becomes a compile error at every switch that forgot it.
Switch expressions were preview in 12 and 13 (with a different break value syntax in 12) and became final in 14.
Picture it A fall-through bug that is silent in the old form and impossible in the new form, and the compile error when a case is missing.
The setup: Q04_Switch.java has an old statement where PLACED forgets its break, and the same logic as a switch expression. It is compiled with --release 13 and --release 14.
public class Q04_Switch {
enum Status { PLACED, PREPARING, DELIVERED, CANCELLED }
static String oldWay(Status s) {
String msg = "?";
switch (s) {
case PLACED:
msg = "waiting";
case PREPARING: // forgot break above: PLACED falls through
msg = "cooking";
break;
case DELIVERED:
msg = "done";
break;
default:
msg = "stopped";
}
return msg;
}
static String newWay(Status s) {
return switch (s) {
case PLACED -> "waiting";
case PREPARING -> "cooking";
case DELIVERED -> "done";
case CANCELLED -> "stopped"; // delete this line: compile error, not a silent bug
};
}
public static void main(String[] args) {
for (Status s : Status.values())
System.out.println(s + ": old=" + oldWay(s) + " new=" + newWay(s));
}
}Make the invisible visible: Compile proofs, then the run.
$ javac --release 13 Q04_Switch.java
Q04_Switch.java:22: error: switch expressions are not supported in -source 13
return switch (s) {
^
(use -source 14 or higher to enable switch expressions)
Q04_Switch.java:23: error: switch rules are not supported in -source 13
case PLACED -> "waiting";
^
(use -source 14 or higher to enable switch rules)
$ javac --release 14 Q04_Switch.java
(compiles)
PLACED: old=cooking new=waiting
PREPARING: old=cooking new=cooking
DELIVERED: old=done new=done
CANCELLED: old=stopped new=stoppedWhat you see: On release 13 the arrow and the expression are not supported. On 14 the file compiles. In the run, PLACED: old=cooking is the bug: the order was only placed, but fall-through carried it into the "cooking" branch. The new form says waiting.
Make the invisible visible: Now delete one case from the new form.
public class Q04_Missing {
enum Status { PLACED, PREPARING, DELIVERED, CANCELLED }
static String f(Status s) {
return switch (s) {
case PLACED -> "waiting";
case PREPARING -> "cooking";
case DELIVERED -> "done";
};
}
public static void main(String[] a) { System.out.println(f(Status.PLACED)); }
}$ javac --release 25 Q04_Missing.java
Q04_Missing.java:4: error: the switch expression does not cover all possible input values
return switch (s) {
^Why: The compiler refuses to guess a value for CANCELLED. In the old statement the same omission compiles and returns whatever the default was.
Statement
Assign in each branch, remember break.
String msg;
switch (s) {
case PLACED:
msg = "waiting";
break;
case PREPARING:
msg = "cooking";
break;
default:
msg = "?";
}Expression
One value out, no break.
String msg = switch (s) {
case PLACED -> "waiting";
case PREPARING -> "cooking";
case DELIVERED, CANCELLED -> "done";
};The shift: The result of the switch is the value, so there is no variable to forget and no break to forget.
Land it Switch expressions removed fall-through, removed the assign-in-every-branch pattern and made the compiler check that every case is covered.
- "When do you use yield?"
-
Use
yieldwhen a branch of a switch expression needs more than one statement. The arrow can point at a single expression. For anything longer you open a block with braces and end it withyield value;, which is the switch-expression version ofreturn.A typical case is a branch that logs, computes and then returns:
a switch branch with yieldruns offlinecase PREPARING -> { log.info("cooking"); yield estimate(order); }Without
yieldyou would have had to compute outside the switch.The older colon form also works in an expression:
case PLACED: yield "waiting";. That form still falls through if you forget theyield, but the compiler would complain that the branch does not produce a value, so it is much safer than the statement.My style is to keep arrow branches to one expression and move longer logic into a method. If a branch needs a block with
yieldin five places, the switch is doing too much. - "Does a switch expression need a default?"
-
Only when the compiler cannot prove every value is covered. For an
intor aStringyou must adddefault, because the set of values is open. For anenum, the compiler knows all constants, so listing them all is enough. For a sealed interface (question 8) it knows all permitted subtypes.When you leave
defaultout on an enum and cover everything, there is a hidden safety net. If someone addsREFUNDEDnext month, this switch stops compiling and the compiler points at the exact line. Adefault -> "?"would swallow the new value silently.So
defaultis not "free insurance". For types you own, leaving it out is often the more careful choice. For types you do not own, or open ones such as strings, you need it.At run time an exhaustive enum switch also has a last-resort branch that throws if a new constant appears in a library compiled later. You rarely see that, and it is another reason not to hide mistakes with a catch-all.
- "What is the difference between case A -> and case A: in a switch expression?"
-
The arrow form never falls through and each case is its own branch. The colon form is the old style, even inside an expression: execution continues into the following case unless you
yieldorbreakout. You cannot mix the two forms in one switch.Arrow cases can be a single expression, a block or a
throw.case CANCELLED -> throw new IllegalStateException();is common and lets you reject values without writing a branch value.Use the arrow form almost always. The colon form is useful in two cases: when you really want fall-through, which is rare, and when you are converting a long old statement and want to keep the shape for a clean diff.
One more difference: arrow cases do not share variable scope. A variable declared in one arrow block is invisible to the next case, while in colon form all cases share one scope and a declaration can leak into the next case. That leak is another source of old bugs.
- "Can I use a switch expression on strings or integers?"
-
Yes. The selector can be
int,char,String(since Java 7), an enum, or any type if you use pattern matching (Java 21, question 7). Because the set of ints or strings is open, you must supply adefault.Multiple labels work:
case "SAT", "SUN" -> "weekend";. And since Java 21 you can matchnullexplicitly withcase null -> .... Without that, anullselector throwsNullPointerException, just as in the old statement.One common misuse is to build a switch on strings for something that deserves an enum. A typo such as
"DELIVERD"compiles and silently takes the default. If the set is fixed, an enum or sealed type gets compiler checking, while a string switch gets none.I use string switches for parsing external input (commands, headers), then convert to an enum as early as possible.
Q5. "Text blocks (Java 15): what do they solve, and how is the indentation decided?"
Reveal answer
Strong answer A text block is a multi-line string literal written between triple quotes """. It solves the pain of embedding JSON, SQL, HTML or log samples in Java: no \n at the end of every line, no + between lines, and no backslash before every double quote.
The text starts on the line after the opening """. Each line break in the source becomes a \n in the string. Quotes inside need no escaping unless you write three in a row.
The indentation rule is the part people forget. The compiler looks at every non-blank line and at the line holding the closing """. It finds the smallest indent among them and removes that many leading spaces from every line. This is called incidental whitespace stripping. Whatever indent is left over is part of the string.
So the closing delimiter is a ruler. Put it at the same column as the text and nothing is left over. Move it left and every line keeps the difference as real spaces. Put the closing quotes on the last text line and there is no trailing newline.
Trailing spaces on each line are removed. Use \s to keep one, and a backslash at the end of a line to join it with the next. Text blocks were preview in 13 and 14 and are final in 15.
Picture it Three blocks with different closing positions show exactly what the rule keeps and drops.
The setup: Q05_TextBlock.java compares an old concatenated JSON string with its text block, then prints three blocks where the closing quotes move. Lines are shown between | bars so the spaces are visible.
public class Q05_TextBlock {
public static void main(String[] args) {
String old = "{\n" +
" \"order\": 7,\n" +
" \"restaurant\": \"Pizza Lane\"\n" +
"}\n";
String block = """
{
"order": 7,
"restaurant": "Pizza Lane"
}
""";
System.out.println(old.equals(block));
String a = """
two spaces kept
closing quotes sit left of the text
""";
String b = """
both lines lose 12 spaces
this one keeps 2
""";
String c = """
no trailing newline""";
show("a", a); show("b", b); show("c", c);
System.out.println("escapes: [" + """
kept \s
joined \
on one line""" + "]");
}
static void show(String n, String s) {
System.out.println(n + ":"); s.lines().forEach(l -> System.out.println("|" + l + "|"));
System.out.println(" ends with newline? " + s.endsWith("\n"));
}
}Make the invisible visible: Release 14 refuses it, release 15 accepts it, and the run shows the whitespace.
$ javac --release 14 Q05_TextBlock.java
Q05_TextBlock.java:7: error: text blocks are not supported in -source 14
String block = """
^
(use -source 15 or higher to enable text blocks)
$ javac --release 15 Q05_TextBlock.java
(compiles)
true
a:
| two spaces kept|
|closing quotes sit left of the text|
ends with newline? true
b:
|both lines lose 12 spaces|
| this one keeps 2|
ends with newline? true
c:
|no trailing newline|
ends with newline? false
escapes: [kept
joined on one line]What you see: true: the text block equals the old concatenation. In block a the closing quotes sit left of the text, so the first line keeps two spaces. In b the closing quotes align with the text, so twelve spaces vanish from both lines and the second line keeps its extra two. In c the closing quotes are on the last line, so there is no final newline. The last output line shows \s keeping a space and a backslash joining two lines.
Why: There is no setting. The position of the closing delimiter is the setting, and your editor's indent when you paste the block does not change the string.
String +
Quotes and newlines by hand.
String json = "{\n" +
" \"order\": 7,\n" +
" \"city\": \"Mysuru\"\n" +
"}\n";Text block
Write it as it looks.
String json = """
{
"order": 7,
"city": "Mysuru"
}
""";The shift: The source now looks like the string it produces, so a reviewer can check it by eye.
Land it A text block is a multi-line literal whose indent is measured against the closing quotes, so I place those quotes to decide what stays.
- "How do I put variables into a text block?"
-
A text block is still just a string, so you use
formatted(Java 15) orString.format. For example"""\n {"id": %d}\n """.formatted(7). Be careful that%inside the text must be written%%when you format.Java 21 previewed string templates (
STR."...") as a built-in way to do this, but the feature was withdrawn and never shipped, so do not use it and do not expect it in 25.For SQL, remember that text blocks make formatting nice but do not make injection safe. Never paste user input into the text. Use a
PreparedStatementwith?placeholders in the block, and link the parameters separately. Chapter E8 covers this in detail.For JSON, build it with a library (Jackson) in production code. Text blocks are best for tests, fixtures and small constants where the shape matters more than the values.
- "Does a text block keep my line endings, and what about tabs?"
-
Every line break in the source becomes a plain
\nin the string, no matter whether your file was saved with Windows (\r\n) or Unix endings. That makes text blocks stable across operating systems, which a string built withSystem.lineSeparator()is not.Tabs and spaces both count as one character of whitespace when the compiler measures indentation. Mixing them in one block gives confusing results, because a line indented with one tab looks deeper than a line with four spaces but counts as one character less. Use one kind throughout. Most teams use spaces.
Trailing whitespace at the end of each line is stripped, which protects you from invisible diffs. If you need a trailing space, write
\s.If you need the string to have no line breaks, end each line with a backslash. That joins the lines, and it is handy for a long single-line message.
- "Can I use a text block as an annotation value or a switch case label?"
-
Yes, it is an ordinary compile-time constant string. That means you can use it in an annotation (
@Query("""...""")in Spring Data), as astatic finalconstant, or even as acaselabel if it is a constant.The Spring Data case is the most common one. A long native SQL query inside
@Queryis far easier to read as a text block than as a chain of concatenated strings, and because it is constant, the compiler checks nothing extra but reflection reads it normally.One thing to watch: constants are built by the compiler, so the indentation-stripping happens at compile time, not at run time. There is no run-time cost, and no way for the stripping to differ between machines.
The only things you cannot do in a text block are embed unescaped three-quote sequences and start the text on the same line as the opening quotes. The opening delimiter must be followed by a line break.
- "How do text blocks interact with escape sequences?"
-
All the normal escapes work:
\n,\t,\"and\\. Two new ones were added for text blocks:\sfor a space that survives the trailing-whitespace strip, and a backslash at the end of a line to join the next line.The order of processing matters in rare cases. The compiler first removes incidental indentation and trailing spaces, then interprets escapes. That is why
\sworks: it is still written as two characters while the stripping runs, and becomes a real space only afterwards.If you need the stripping or the escape processing at run time, for text from a file for instance, the String class has
stripIndent()andtranslateEscapes()(both Java 15), which apply exactly the same two steps. That is how you can reproduce text-block behaviour on text loaded from a resource file.Rule of thumb: do not escape quotes in a text block, write real ones, and use
\sonly when a trailing space is meaningful.
Q6. "Records (Java 16): what do you get for free, and what can a record not do?"
Reveal answer
The real test Whether you can say a record is a transparent, shallowly immutable data carrier and list both the generated members and the hard limits, instead of "it is a class with less code".
Strong answer A record is a class whose only job is to hold a fixed set of values. You write record Line(String item, int qty, int priceCents) {} and the compiler generates the rest: a private final field for each component, a constructor that takes all of them, an accessor method for each (named item(), not getItem()), plus equals, hashCode and toString that compare and print every component.
You can add to it. A compact constructor (no parameter list) runs before the fields are assigned, which is the place for validation or tidying: if (qty <= 0) throw .... You can add normal methods, static methods, static fields, nested types, and implement interfaces.
What a record cannot do: it cannot extend another class (it already extends java.lang.Record), it cannot declare extra instance fields, and its fields cannot be changed after construction. It is also implicitly final, so nothing can extend it.
Two cautions. Records are shallowly immutable: a record holding a List still lets someone change the list. Copy it with List.copyOf in the compact constructor. And records are for plain data. If an object has behaviour, identity or changing state, a normal class is still right.
Records were preview in 14 and 15 and final in 16.
Picture it A record validates, tidies its input, compares by value and prints itself. A second file shows the three things the compiler refuses.
The setup: Q06_Record.java declares Line with a compact constructor that rejects zero quantity and strips the item name. --release 15 fails and --release 16 compiles it.
import java.util.*;
public class Q06_Record {
record Line(String item, int qty, int priceCents) {
Line { // compact constructor: validate
if (qty <= 0) throw new IllegalArgumentException("qty must be positive: " + qty);
item = item.strip(); // may reassign parameters
}
int totalCents() { return qty * priceCents; } // methods are fine
static Line of(String item) { return new Line(item, 1, 0); }
}
public static void main(String[] args) {
var a = new Line(" biryani ", 2, 24900);
var b = new Line("biryani", 2, 24900);
System.out.println(a); // toString
System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()));
System.out.println(a.item() + " " + a.totalCents()); // accessor is item(), not getItem()
var set = new HashSet<>(List.of(a, b));
System.out.println("set size " + set.size());
try { new Line("x", 0, 1); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
}Make the invisible visible: Compile proof and run.
$ javac --release 15 Q06_Record.java
Q06_Record.java:4: error: records are not supported in -source 15
record Line(String item, int qty, int priceCents) {
^
(use -source 16 or higher to enable records)
... (6 more errors trimmed)
$ javac --release 16 Q06_Record.java
(compiles)
Line[item=biryani, qty=2, priceCents=24900]
true true
biryani 49800
set size 1
qty must be positive: 0What you see: a was built with " biryani " and b with "biryani". The compact constructor stripped the space, so a.equals(b) is true, the hashes match, and a HashSet of both has size 1. The accessor is item().
Make the invisible visible: What a record refuses.
public class Q06_RecordBad {
record A(int x) { int extra; } // no instance fields
record B(int x) extends Object {} // cannot extend
record C(int x) { void set(int v) { this.x = v; } } // fields are final
public static void main(String[] a) {}
}$ javac --release 25 Q06_RecordBad.java
Q06_RecordBad.java:2: error: field declaration must be static
record A(int x) { int extra; } // no instance fields
^
(consider replacing field with record component)
Q06_RecordBad.java:3: error: '{' expected
record B(int x) extends Object {} // cannot extend
^Why: Each refusal protects the record's promise: the state is exactly the declared components, set once. A second field or a setter would break the guarantee that two equal-looking records are equal.
Java 8 class
About forty lines in real code.
public final class Line {
private final String item;
private final int qty;
public Line(String item, int qty) {
this.item = item; this.qty = qty;
}
public String getItem() { return item; }
public int getQty() { return qty; }
// equals, hashCode, toString ...
}Java 16 record
One line, same behaviour.
public record Line(String item, int qty) {}
// accessors: item(), qty()
// equals, hashCode, toString: generatedThe shift: Everything you would copy from the IDE generator is now written by the compiler and cannot go stale.
Land it A record is a final, shallowly immutable data class with generated members, and what it cannot do is extend, add fields or change state.
- "Is a record deeply immutable?"
-
No. Only the reference stored in each field is final. If a component is a mutable object, such as a
List, an array or aDate, anyone holding the record can change what is inside it, and the record'sequalsandhashCodewill change with it.For example
record Order(int id, List<Line> lines)built with anArrayListlets the caller keep that list and add a line later. The fix is a compact constructor that copies:lines = List.copyOf(lines);. That gives an unmodifiable copy and also rejectsnullelements.Arrays are the worst case, because the generated
equalscompares array references, not contents, andtoStringprints something like[I@1b2c. If you must hold an array, override those methods or use a list instead.My checklist for each record: are all components immutable types? If not, copy defensively in the compact constructor.
- "Can a record implement an interface, have static methods, or be generic?"
-
All three, yes. A record can implement any number of interfaces, which is how records often join a sealed hierarchy (
record Upi(String handle) implements Payment). It can have static factory methods and static fields. And it can be generic:record Pair<A, B>(A first, B second) {}.It can also have extra instance methods, including derived values like
totalCents()computed from the components. What it cannot have is extra instance fields, because then the state would no longer be fully described by the header.You can also add a second, non-canonical constructor, but it must start by calling the canonical one with
this(...). That is how you give a default:Line(String item) { this(item, 1, 0); }.Nested records are implicitly static, so a record inside a class does not hold a reference to the outer object. That surprises people coming from inner classes.
- "Do records work with Jackson, JPA and Spring?"
-
Jackson supports records from 2.12, so a record can be a request or response body and it deserialises through the canonical constructor. Spring Boot with a recent Jackson handles this out of the box. Records make good DTOs for exactly that reason.
JPA is the exception. A JPA entity needs a no-argument constructor, mutable fields so the provider can set them, and often a proxy subclass for lazy loading. A record has none of those, so it cannot be an entity. You can use a record for a projection (a query that returns some columns) or as an embeddable value in newer providers.
With Spring Data and Hibernate, a record is a fine result type for a read-only query that selects a few fields.
The rule I give juniors: records for data in and out (DTOs, events, query rows, value objects), classes for entities with identity and lifecycle. Chapter E4 shows the Spring side.
- "What is the difference between a record and Lombok's @Value?"
-
A record is part of the language, so it needs no annotation processor, works in every tool and IDE, and the compiler guarantees its shape. Lombok
@Valuerewrites your class during compilation, which means your build depends on Lombok and some tools struggle with the generated code.Differences in what you get: a record's accessors are
item(), while Lombok createsgetItem(). A record is always final and cannot extend a class, but a Lombok class can extend. Lombok offers extras such as builders and@With, which records do not.Records also take part in newer language features: record patterns (question 9) let you take a record apart in
instanceofandswitch, and Lombok classes do not.For new code on Java 17 or later I choose records for data carriers and keep Lombok only where I really need builders, or where older code already depends on it.
Q7. "Pattern matching for instanceof (16) and for switch (21) — show before and after."
Reveal answer
Strong answer Pattern matching removes the "test, then cast" ritual. The old code asked if (o instanceof Placed), then wrote a cast on the next line: Placed p = (Placed) o;. The test and the cast said the same thing twice, and a copy-paste error could make them disagree.
Java 16: if (o instanceof Placed p) { ... p.orderId() ... }. If the test succeeds, the variable p is already of the right type, and it is in scope exactly where the test is known to be true. You can chain a condition: o instanceof Cancelled c && c.reason().length() > 5.
Java 21: the same idea inside switch. case Placed p -> ... tests the type and binds the variable. You can add a guard: case Placed p when p.totalCents() > 50000 -> .... Guards are checked in order, so the specific case goes first.
Combined with a sealed interface (question 8), the compiler also checks that you handled every subtype, with no default. That turns "I think I covered all the cases" into a compile error when you did not.
null note: a pattern switch still throws NullPointerException on a null selector unless you write case null.
Picture it An event type handled the Java 8 way and the Java 21 way, with compile proofs for both steps.
The setup: Q07_Patterns.java has before (instanceof plus casts) and after (pattern switch with a guard) over a sealed Event interface. It is compiled with --release 20 and --release 21.
import java.util.*;
public class Q07_Patterns {
sealed interface Event permits Placed, Cancelled, Delivered {}
record Placed(int orderId, int totalCents) implements Event {}
record Cancelled(int orderId, String reason) implements Event {}
record Delivered(int orderId, int minutes) implements Event {}
static String before(Object o) { // Java 8 style
if (o instanceof Placed) {
Placed p = (Placed) o;
return "placed " + p.orderId();
} else if (o instanceof Cancelled) {
Cancelled c = (Cancelled) o;
return "cancelled: " + c.reason();
}
return "other";
}
static String after(Event e) { // Java 21 style
return switch (e) {
case Placed p when p.totalCents() > 50000 -> "BIG order " + p.orderId();
case Placed p -> "placed " + p.orderId();
case Cancelled c -> "cancelled: " + c.reason();
case Delivered d -> "delivered in " + d.minutes() + " min";
};
}
public static void main(String[] args) {
Object o = new Cancelled(3, "customer changed mind");
if (o instanceof Cancelled c && c.reason().length() > 5) // Java 16: test, cast, bind
System.out.println("long reason: " + c.reason());
System.out.println(before(new Placed(1, 100)));
for (Event e : List.of(new Placed(1, 54700), new Placed(2, 29700),
new Cancelled(3, "late"), new Delivered(4, 31)))
System.out.println(after(e));
}
}Make the invisible visible: Compile proofs and the run.
$ javac --release 20 Q07_Patterns.java
Q07_Patterns.java:22: error: patterns in switch statements are not supported in -source 20
case Placed p when p.totalCents() > 50000 -> "BIG order " + p.orderId();
^
(use -source 21 or higher to enable patterns in switch statements)
$ javac --release 21 Q07_Patterns.java
(compiles)
long reason: customer changed mind
placed 1
BIG order 1
placed 2
cancelled: late
delivered in 31 minWhat you see: Release 20 rejects patterns in switch; 21 accepts them. The run shows the guard: order 1 (₹547.00, above the ₹500.00 limit in the code) matched the BIG case, and order 2 (₹297.00) fell to the plain Placed case. Then the instanceof step alone, with its own proof:
$ javac --release 15 Q07_Instanceof.java
Q07_Instanceof.java:4: error: pattern matching in instanceof is not supported in -source 15
if (o instanceof String s && s.length() > 3) System.out.println(s.toUpperCase());
^
(use -source 16 or higher to enable pattern matching in instanceof)
$ javac --release 16 Q07_Instanceof.java
(compiles)
BIRYANIWhy: instanceof patterns arrived in 16 and switch patterns in 21, five releases later. Checking which one you have matters when a library targets Java 17.
Before
Test, then cast, twice.
if (o instanceof Placed) {
Placed p = (Placed) o;
return p.orderId();
} else if (o instanceof Cancelled) {
Cancelled c = (Cancelled) o;
return c.orderId();
}
return -1;After
Bind in the test.
return switch (e) {
case Placed p -> p.orderId();
case Cancelled c -> c.orderId();
case Delivered d -> d.orderId();
};The shift: The type test and the typed variable are now one step, and the switch checks that no subtype was forgotten.
Land it Pattern matching ties the type test and the typed variable together, first in instanceof (16) and then in switch with guards (21).
- "What is the scope of the pattern variable, and why does it sometimes seem to leak?"
-
The variable exists only where the compiler can prove the test passed. In
if (o instanceof Placed p) { ... }it is in scope inside the block. It is also in scope in the rest of an&&chain on the same line.The surprising case is the negated form:
if (!(o instanceof Placed p)) return; p.orderId();. After theif, the method continues only when the test was true, sopis in scope below it. That is called flow scoping, and it is how you write a guard clause without nesting.It never leaks into code where the test might have failed.
if (o instanceof Placed p || x)does not give youpinside the block, because the right side of||could be the reason you got in.My practice: keep the pattern variable names short and local, and use early return for the negated form when it removes an indentation level.
- "What is a guard, and what is dominance?"
-
A guard is the
whencondition after a pattern:case Placed p when p.totalCents() > 50000. The case matches only if the type matches and the condition is true.Dominance is a compile error you get when an earlier case already covers a later one. If you write
case Placed p ->first andcase Placed p when ... ->second, the second can never run, so the compiler refuses the file. The cure is to put the guarded, more specific case first.The same rule applies across the hierarchy.
case Object oplaced beforecase String swould swallow everything, so it is rejected.This matters because the order of cases now carries meaning. In the old switch, order mattered only for fall-through. With patterns, order is the priority list, so I read a pattern switch top to bottom like a series of
ifstatements. - "Does pattern matching replace polymorphism and the visitor pattern?"
-
It replaces the need for the visitor in one common situation: a closed set of data types that you process in several different ways. A sealed interface plus a pattern
switchgives the same dispatch with far less code, and the compiler checks completeness.It does not replace normal polymorphism. If each type has its own behaviour and callers should not care which type they have, put the method on the interface and let the objects do the work. A
switchon type that grows everywhere is a smell in that situation.The rule I use: if the data types belong to you and the operations keep changing, use records, sealed types and switch. If the operations are fixed and the types keep being added, use interfaces and methods.
In practice a project uses both. Domain objects with behaviour use methods, and events, commands and results use records with pattern switches.
- "What does a pattern switch do with null?"
-
It throws
NullPointerExceptionunless you add acase nullbranch. That is the same behaviour as the old switch, kept so existing code does not change meaning.You can write
case null -> "no event";as a separate branch, or combine it with the default:case null, default -> "unknown";. Use the combined form only when you really treat a missing value and an unknown value the same way.The
instanceofpattern is null-safe by nature.null instanceof Placed pis simply false, so the code inside the block never sees a null.My habit is to reject nulls at the boundary of a method with
Objects.requireNonNulland keep the switch clean. When null is a legal value for the data, I addcase nullso that the meaning is written on the page, not hidden in an exception.
Q8. "Sealed classes (Java 17): what do they enable when combined with switch?"
Reveal answer
Strong answer A sealed class or interface lists exactly which classes may extend or implement it: sealed interface Payment permits Upi, Card, Cash {}. Nobody else can add a fourth one. The compiler knows the complete list.
That knowledge is what switch uses. When you switch over a sealed type and cover every permitted subtype, the compiler accepts the switch with no default. When you later add Wallet to the permits list and forget a switch, the file stops compiling and points to the exact line. Without sealing, the same omission is a silent bug in production.
Each permitted subtype must be declared final, sealed again or non-sealed. Records are implicitly final, so a record is the natural subtype. In the same file, you may omit the permits clause and the compiler infers the list.
The combination is Java's version of an algebraic data type: a value is exactly one of a fixed set of shapes, and a switch takes it apart. Use it for events, commands, results (success or failure) and payment methods. Do not use it for a type that plugins or other modules must extend.
Sealed classes were preview in 15 and 16 and final in 17. Pattern switch over them needs Java 21.
Picture it A payment type with three subtypes, a switch with no default, and the compile error when a fourth subtype appears.
The setup: Q08_SealedOnly.java shows sealed declarations by themselves (proof for 16 vs 17). Q08_Sealed.java adds the pattern switch (needs 21). Q08_Wallet.java adds a Wallet subtype and forgets one case.
public class Q08_SealedOnly {
sealed interface Payment permits Upi, Card, Cash {}
record Upi(String handle) implements Payment {}
record Card(String last4) implements Payment {}
record Cash() implements Payment {}
// class Crypto implements Payment {} // would not compile: not in the permits list
public static void main(String[] args) {
Payment p = new Upi("asha@bank");
System.out.println(p + " permits: "
+ java.util.Arrays.stream(Payment.class.getPermittedSubclasses()).map(Class::getSimpleName).toList());
}
}public class Q08_Sealed {
sealed interface Payment permits Upi, Card, Cash {}
record Upi(String handle) implements Payment {}
record Card(String last4, int emiMonths) implements Payment {}
record Cash() implements Payment {}
static int feeCents(Payment p, int amount) {
return switch (p) { // no default: the compiler checks all three
case Upi u -> 0;
case Card c -> c.emiMonths() > 0 ? amount / 50 : amount / 100;
case Cash x -> 2500;
};
}
public static void main(String[] args) {
System.out.println(feeCents(new Upi("asha@bank"), 54700));
System.out.println(feeCents(new Card("4242", 3), 54700));
System.out.println(feeCents(new Cash(), 54700));
}
}Make the invisible visible: Compile proofs for the declarations, then for the switch, then the run.
$ javac --release 16 Q08_SealedOnly.java
Q08_SealedOnly.java:2: error: sealed classes are not supported in -source 16
sealed interface Payment permits Upi, Card, Cash {}
^
(use -source 17 or higher to enable sealed classes)
... (1 more errors trimmed)
$ javac --release 17 Q08_SealedOnly.java
(compiles)
Upi[handle=asha@bank] permits: [Upi, Card, Cash]
$ javac --release 17 Q08_Sealed.java
Q08_Sealed.java:9: error: patterns in switch statements are not supported in -source 17
case Upi u -> 0;
^
(use -source 21 or higher to enable patterns in switch statements)
$ javac --release 21 Q08_Sealed.java
(compiles)
0
1094
2500What you see: Release 16 rejects sealed; release 17 compiles it, and getPermittedSubclasses() lists Upi, Card, Cash. The switch over those three needs release 21 because it uses patterns. The fees print as 0, 1094 and 2500.
Make the invisible visible: Now the file where Wallet was added and the switch was not updated.
public class Q08_Wallet {
// Adding a fourth subtype and forgetting the switch:
sealed interface Payment permits Upi, Card, Cash, Wallet {}
record Upi(String handle) implements Payment {}
record Card(String last4) implements Payment {}
record Cash() implements Payment {}
record Wallet(int balance) implements Payment {}
static int fee(Payment p) {
return switch (p) {
case Upi u -> 0;
case Card c -> 100;
case Cash x -> 2500;
};
}
public static void main(String[] args) {}
}$ javac --release 25 Q08_Wallet.java
Q08_Wallet.java:10: error: the switch expression does not cover all possible input values
return switch (p) {
^Why: This is the whole point of sealing. The compiler turns "someone must remember to update every switch" into an error, at the moment the new subtype is added.
Open
Anyone can add a subtype.
interface Payment {}
class Upi implements Payment {}
class Card implements Payment {}
// switch needs a default
// because a Crypto may appearSealed
The list is closed.
sealed interface Payment
permits Upi, Card, Cash {}
record Upi(String h) implements Payment {}
record Card(String l4) implements Payment {}
record Cash() implements Payment {}
// no default needed in a switchThe shift: Closing the list lets the compiler prove a switch is complete, so it can check your work.
Land it Sealed types give a closed list of subtypes, so a pattern switch needs no default and any missing case becomes a compile error.
- "Why not just use an enum?"
-
An enum is a closed list of constants. Every value has the same shape: a name and maybe a few shared fields. A sealed hierarchy is a closed list of types, and each type can carry different data.
Upiholds a handle,Cardholds the last four digits and an EMI count, andCashholds nothing.If every case is just a label (
PLACED,DELIVERED), use an enum. If different cases carry different fields, an enum forces you to add nullable fields for all of them, which is the classic design smell.Sealed types with records give you that variety and the same exhaustiveness check an enum has.
A good test: if you find yourself writing "this field is only used when type is X", you want a sealed hierarchy.
- "What are final, sealed and non-sealed for the subtypes?"
-
Each permitted subtype must say how far the closing goes.
finalmeans no further subtypes, and every record is already final.sealedmeans this subtype is itself closed and lists its own permitted children.non-sealedmeans "the closed list ends here: this branch is open again".Use
non-sealedsparingly. A switch can no longer prove completeness below that point, so it needs a case or default for the open subtype. It is useful when you want a closed set of top-level categories but let plugins extend one category.The subtypes must be in the same module (or, with no modules, the same package) as the sealed type. That is how the compiler guarantees the list is really complete.
In a single file, you can leave out
permits: nested subtypes in the same compilation unit are picked up automatically. - "How does sealed interact with JSON, databases or libraries I do not control?"
-
The sealing is a compile-time promise, so anything that creates instances from outside your code, such as a JSON parser, has to be told which subtype to create. Jackson needs
@JsonTypeInfoand@JsonSubTypesto choose the subtype from a field such as"type": "UPI". The sealed list and the annotation list must be kept in sync by hand, so I add a test that fails when they differ.Databases are similar. If you store a payment as a row, a discriminator column plays the role of the subtype tag, and the mapping code ends in the same kind of switch.
For code that other teams compile against, sealing is a strong promise. Adding a subtype later breaks every exhaustive switch in their code. That is correct behaviour inside one team and a breaking change across teams.
So I seal types inside an application, and I think twice before sealing anything in a public library.
- "Can a sealed interface be used as a result type, like Success or Failure?"
-
Yes, and it is one of the best uses.
sealed interface Result<T> permits Ok, Err {}withrecord Ok<T>(T value)andrecord Err<T>(String message). A method returns one of them instead of throwing, and the caller must handle both with a switch.That makes the failure path visible in the method's signature, which checked exceptions tried to do and which streams and lambdas made awkward.
Use it for expected failures such as "card declined" or "restaurant closed". Keep exceptions for bugs and for things the caller cannot reasonably handle, like a lost database connection.
A small caveat: generic sealed hierarchies and record patterns together can need a little care in type inference, but a plain
case Ok<T>(var v)works in Java 21 and later.
Q9. "Record patterns (21) and unnamed variables _ (22): how do they work together?"
Reveal answer
Strong answer A record pattern takes a record apart while testing its type. Instead of case Placed p -> p.order().id(), you write case Placed(Order(int id, ...), int total) -> .... The compiler checks the type, calls the accessors for you, and gives each component a name you can use. Patterns nest as deep as the data does.
The problem it creates is clutter: you often care about two components out of five, but a pattern must account for all of them. That is what unnamed variables and patterns fix. The single underscore _ says "there is a value here and I am not going to use it". It is final since Java 22 (preview in 21).
Where _ is allowed: a pattern component (Order(int id, _, _)), a local variable you must declare but never read (for (var _ : list)), a catch parameter (catch (NumberFormatException _)), a lambda parameter, and a try-with-resources variable. You can also write a bare _ alone as a pattern to match anything without a type.
Together they let a switch read like the shape of the data: case Placed(Order(int id, _, _), _) -> "order " + id. The compiler still checks exhaustiveness through the nesting, so a missing case is still an error.
Record patterns were preview in 19 and 20 and final in 21. Unnamed variables were preview in 21 and final in 22.
Picture it A nested event is taken apart in one pattern, with _ for the parts that are not needed, and a compile proof across three releases.
The setup: Q09_RecordPatterns.java has Point, Order and a sealed Event. The switch takes an event, its order and the order's drop-off point apart in a single pattern, with a guard.
import java.util.*;
public class Q09_RecordPatterns {
record Point(int x, int y) {}
record Order(int id, Point dropoff, String status) {}
sealed interface Event permits Placed, Cancelled {}
record Placed(Order order, int totalCents) implements Event {}
record Cancelled(Order order, String reason) implements Event {}
static String describe(Event e) {
return switch (e) {
case Placed(Order(int id, Point(int x, var y), _), int total) when total > 50000
-> "order " + id + " big, drop at x=" + x; // y and status ignored
case Placed(Order(int id, _, _), _) -> "order " + id + " placed";
case Cancelled(Order o, _) -> "order " + o.id() + " cancelled";
};
}
public static void main(String[] args) {
var o = new Order(7, new Point(12, 80), "PREPARING");
System.out.println(describe(new Placed(o, 79800)));
System.out.println(describe(new Placed(o, 1200)));
System.out.println(describe(new Cancelled(o, "late")));
int count = 0;
for (var ev : List.of(new Placed(o, 1), new Cancelled(o, "x"))) { count++; } // _ also works as a loop variable
for (var _ : List.of(1, 2, 3)) count++;
System.out.println("count " + count);
try { Integer.parseInt("x"); } catch (NumberFormatException _) { System.out.println("bad number ignored"); }
}
}Make the invisible visible: Compile it with 20, 21 and 22, then run.
$ javac --release 20 Q09_RecordPatterns.java
Q09_RecordPatterns.java:12: error: patterns in switch statements are not supported in -source 20
case Placed(Order(int id, Point(int x, var y), _), int total) when total > 50000
^
(use -source 21 or higher to enable patterns in switch statements)
Q09_RecordPatterns.java:12: error: deconstruction patterns are not supported in -source 20
case Placed(Order(int id, Point(int x, var y), _), int total) when total > 50000
^
(use -source 21 or higher to enable deconstruction patterns)
... (1 more errors trimmed)
$ javac --release 21 Q09_RecordPatterns.java
Q09_RecordPatterns.java:12: error: unnamed variables are not supported in -source 21
case Placed(Order(int id, Point(int x, var y), _), int total) when total > 50000
^
(use -source 22 or higher to enable unnamed variables)
$ javac --release 22 Q09_RecordPatterns.java
(compiles)
order 7 big, drop at x=12
order 7 placed
order 7 cancelled
count 5
bad number ignoredWhat you see: Release 20 rejects the record pattern, release 21 accepts the pattern but rejects _ ("unnamed variables are not supported in -source 21"), and release 22 compiles all of it. The run prints x=12 from deep inside the nested data without a single accessor call.
Why: Two features arrived in two different releases, so a team on 21 can destructure records but must still bind every component to a throw-away name. The underscore removes that noise in 22.
Java 17
Accessors, casts, throw-away names.
if (e instanceof Placed p) {
Order o = p.order();
Point d = o.dropoff();
int x = d.x();
return "drop at x=" + x;
}Java 22
One pattern, ignore the rest.
return switch (e) {
case Placed(Order(_, Point(int x, _), _), _)
-> "drop at x=" + x;
default -> "other";
};The shift: Describe the shape you want and name only the pieces you will use.
Land it A record pattern takes nested data apart in one step, and the underscore marks the parts I deliberately ignore.
- "Does a record pattern call the constructor in reverse?"
-
Not exactly. It calls the record's accessor methods, in order, and matches each result against the sub-pattern. For
Point(int x, var y)it callsx()andy(). If you wrote your own accessor, that custom code runs. If an accessor throws, the exception is wrapped in aMatchException.The matching is done only after the outer type test passes, so a
nullrecord never reaches the accessors. Anullcomponent, however, matches a pattern likevar yor a total type pattern, because those accept everything including null.That is why record patterns are only allowed on records. The language needs a guarantee that the accessors mirror the components and have no hidden side effects, and only a record gives it.
In practice, I treat a record pattern as a convenience for reading data. If an accessor does heavy work, I assign it to a variable first.
- "When should I use var inside a record pattern instead of the real type?"
-
varin a pattern copies the component's declared type:Point(var x, var y)on a record of twointcomponents gives you twointvariables. It is shorter and it follows type changes automatically. If someone later changes the component tolong, the pattern still compiles.Writing the type (
int x) is stricter. It documents what you expect, and for generic records it can narrow:Box<String>(String s)tests the content type. For primitives, the written type must match the component exactly in Java 21 to 24, and a preview feature, primitive types in patterns, is widening that.My rule:
varwhen the type is obvious from the record's name, a written type when the type adds information.And use
_instead of either whenever the value is ignored. A named variable that is never read will draw a warning from linters, and the underscore is the compiler-checked way to say it. - "Where else can I use the underscore, and what can I not do with it?"
-
You can use it for any variable that must exist but is never read. In a loop that only counts:
for (var _ : items) count++;. In acatchblock that ignores the exception:catch (NumberFormatException _) { return 0; }. In a lambda where one of two parameters is unused:(_, value) -> value. In atry (var _ = lock.acquire())where the resource is only needed for its cleanup.What you cannot do is read it. There is no way to refer to
_later, so using it in an expression is a compile error. You also cannot declare two unnamed variables in a way that implies they are connected; each one stands alone.Before Java 9 a single underscore was a legal identifier. Java 9 made it an error, and Java 22 gave it this new meaning. If you still have a variable called
_in old code, it will not compile from 9 on.Use it sparingly. The goal is readability: one underscore per ignored thing is clear, a line full of them suggests the pattern is too wide.
- "What happens if a switch over records is not exhaustive?"
-
The compiler rejects it, just as it does for plain sealed types. Exhaustiveness is checked through the nesting. If
EventpermitsPlacedandCancelled, you need cases that cover both, and for each you must cover all possible record values, either with a type pattern that matches everything or with component patterns that together cover all combinations.A guard breaks the proof.
case Placed(Order o, int total) when total > 50000does not cover allPlacedevents, because the compiler does not evaluate the guard. You need anotherPlacedcase without a guard (as the program above does) or adefault.This is the same trade-off as before. Guards give you expressiveness, but they cost you the ability to prove completeness by themselves.
At run time, if a new subtype slips in through separate compilation, the switch throws
MatchException, a last resort that should not happen when you recompile everything together.
Q10. "Sequenced collections (21): what problem did getFirst, getLast and reversed solve?"
Reveal answer
Strong answer Before Java 21, getting the last element of a collection had a different spelling for every type. A List needed list.get(list.size() - 1). A Deque had getLast(). A LinkedHashSet had nothing, so you iterated the whole set. A SortedSet had last(). A LinkedHashMap had no way to ask for its newest entry at all.
Java 21 added three small interfaces: SequencedCollection, SequencedSet and SequencedMap. They say "this collection has a defined first and last element" and give them the same methods: getFirst(), getLast(), addFirst(x), addLast(x), removeFirst(), removeLast() and reversed().
reversed() returns a view, not a copy. It costs nothing to create, and a change to the original shows up in the view and the other way round. For maps, you get firstEntry(), lastEntry(), pollFirstEntry() and putFirst.
List, Deque, LinkedHashSet, LinkedHashMap, SortedSet and SortedMap all implement the new interfaces. HashSet and HashMap do not, because they have no order.
Two edge cases: getFirst() on an empty collection throws NoSuchElementException (it does not return null), and the methods that modify throw UnsupportedOperationException on immutable lists like List.of.
Picture it A queue of customers, a recently-used set and a menu map, using the same method names, with the view behaviour and both failure cases shown.
The setup: Q10_Sequenced.java calls the old and new spelling for the last element, uses addFirst on a LinkedHashSet (impossible before 21), then shows that reversed() follows later changes. Release 20 cannot compile it; 21 can.
import java.util.*;
public class Q10_Sequenced {
public static void main(String[] args) {
List<String> queue = new ArrayList<>(List.of("asha", "ravi", "meera"));
System.out.println(queue.get(queue.size() - 1) + " | " + queue.getFirst() + " | " + queue.getLast());
System.out.println("reversed view: " + queue.reversed());
queue.addFirst("vip");
System.out.println(queue);
var recent = new LinkedHashSet<>(List.of("dosa", "idli", "vada"));
recent.addFirst("pizza"); // before 21: no way to say this
System.out.println(recent + " last=" + recent.getLast());
var view = queue.reversed();
queue.add("kiran"); // the view follows the list
System.out.println("view sees new item: " + view.getFirst());
var menu = new LinkedHashMap<String, Integer>();
menu.put("idli", 49); menu.put("dosa", 99); menu.put("vada", 39);
System.out.println(menu.firstEntry() + " " + menu.lastEntry() + " " + menu.reversed());
var empty = new ArrayList<String>();
try { empty.getFirst(); } catch (NoSuchElementException e) { System.out.println("empty -> " + e); }
try { List.of(1).addFirst(0); } catch (UnsupportedOperationException e) { System.out.println("List.of -> UOE"); }
}
}Make the invisible visible: Compile proof and run.
$ javac --release 20 Q10_Sequenced.java
Q10_Sequenced.java:6: error: cannot find symbol
System.out.println(queue.get(queue.size() - 1) + " | " + queue.getFirst() + " | " + queue.getLast());
^
symbol: method getFirst()
location: variable queue of type List<String>
Q10_Sequenced.java:6: error: cannot find symbol
System.out.println(queue.get(queue.size() - 1) + " | " + queue.getFirst() + " | " + queue.getLast());
^
symbol: method getLast()
location: variable queue of type List<String>
... (10 more errors trimmed)
$ javac --release 21 Q10_Sequenced.java
(compiles)
meera | asha | meera
reversed view: [meera, ravi, asha]
[vip, asha, ravi, meera]
[pizza, dosa, idli, vada] last=vada
view sees new item: kiran
idli=49 vada=39 {vada=39, dosa=99, idli=49}
empty -> java.util.NoSuchElementException
List.of -> UOEWhat you see: On release 20 there are 12 errors, all "cannot find symbol" for getFirst, getLast, reversed and friends. The run shows the same call on a list, a set and a map, and the view view.getFirst() printing kiran after kiran was added to the original list.
Why: The collection types already knew their order. Java 21 only gave that order one set of names, so code that is generic over "anything ordered" can finally be written.
Before 21
Different code for each type.
list.get(list.size() - 1);
deque.getLast();
sortedSet.last();
// LinkedHashSet: loop to the end
for (var x : set) last = x;
// reverse a list: copy and sort
Collections.reverse(copy);Java 21
One name everywhere.
list.getLast();
deque.getLast();
sortedSet.getLast();
linkedHashSet.getLast();
// reversed view, no copy
list.reversed();The shift: The same question gets the same method name on every ordered collection.
Land it Sequenced collections give every ordered collection the same first, last and reversed methods, with reversed as a live view.
- "Is reversed() a copy?"
-
No, it is a live view. Creating it takes constant time no matter how big the collection is, and it shares storage with the original. If you add
kiranto the original list, the reversed view already shows it first, as the output above proves. If you modify through the view (a view of a modifiable list is modifiable), the original changes too.This is cheap and handy when you only need to iterate backwards:
for (var x : list.reversed())costs nothing. The old way,Collections.reverse(copy), copied the whole list first.If you want an independent reversed list, copy it explicitly:
new ArrayList<>(list.reversed())orlist.reversed().stream().toList().Because it is a view, be careful when you pass it to code that keeps it for later while the original keeps changing. If another thread modifies the original, the view has the same thread-safety as the original, which for
ArrayListmeans none. - "Which collections do NOT have first and last, and what do I do?"
-
HashSetandHashMapare built for speed and have no defined order, so asking for "the first" would be meaningless. They are not sequenced and have nogetFirst.TreeSetandTreeMapare sequenced, with the sorted order as the sequence.ArrayDequeis sequenced (it is aDeque).PriorityQueueis not, because its iteration order is not its priority order.If you have a
HashSetand need "the first", the real answer is that you chose the wrong set. UseLinkedHashSetif insertion order matters orTreeSetif sorted order matters. The decision is made at the point you create the collection.A small trap:
Set.of(...)andMap.of(...)have an order that changes between JVM runs on purpose, so never rely on any "first" element of them. - "Can I add or remove at the front of a List now?"
-
Yes, for lists that support changes.
list.addFirst(x)andlist.removeFirst()work onArrayListandLinkedList. ForLinkedListthis is fast, because it is a linked structure. ForArrayListit works but shifts every element, so it is O(n), and you should not use it in a hot loop. The method name hides that cost.On an immutable list such as
List.ofor the result ofStream.toList(), these methods throwUnsupportedOperationException, as the last line of the run shows. Reading methods likegetFirststill work.For a real queue, use
ArrayDeque, which is fast at both ends. The new methods are a consistent naming layer, not a performance upgrade.The naming consistency matters more than it looks: utility code can now accept a
SequencedCollectionand work for lists, deques and linked sets alike. - "Do I need to change my code or libraries to benefit?"
-
Only if you want the new methods. Existing code compiles and runs unchanged, because the new interfaces are added to the old types without removing anything.
There is one compatibility trap. If you had your own class that extends or implements
Listand also defined a method calledgetFirst()orreversed()with a different return type, the upgrade can break compilation. A few libraries had to adjust for that in 21.Mixed Java and Kotlin projects deserve a test run too, because the Kotlin standard library has its own
first()andlast()helpers on lists and the new JDK members can change which call is chosen. Check the release notes of your Kotlin version.The advice I give: upgrade, compile, run the tests, and then replace
list.get(list.size() - 1)withgetLast()in code you are touching anyway. Do not mass-rewrite.
These eight questions cover the small additions that are not headline features but are in daily use. Interviewers use them to see whether you actually read release notes.
Q11. "Which String methods arrived after Java 8, and which do you use every day?"
Reveal answer
Strong answer Eight methods or families are worth knowing by version. Java 11: isBlank() (true for empty or only whitespace), strip(), stripLeading(), stripTrailing(), repeat(n) and lines(). Java 12: indent(n) and transform(fn). Java 15: formatted(args), stripIndent() and translateEscapes(). Java 21: indexOf(ch, from, to), splitWithDelimiters and StringBuilder.repeat.
The ones I use daily are isBlank(), strip(), repeat(), lines() and formatted(). isBlank() replaces trim().isEmpty(). strip() replaces trim() and differs in an important way: trim() removes only characters up to code point 32 (ASCII spaces and control characters), while strip() removes all Unicode whitespace, such as the em space or the non-breaking space.
repeat(n) gives separators and padding without a loop: "-".repeat(40). lines() returns a Stream<String> that splits on \n, \r and \r\n, which is more reliable than split("\n"). formatted is String.format as an instance method.
The ones I rarely use: indent (handy for generating nested text), transform (apply a function in a chain) and stripIndent.
Picture it The difference between trim and strip is invisible on the screen, so a program prints it with a Unicode em space.
The setup: Q11_Strings.java tests isBlank against a string of spaces and an em space (\u2003), compares trim with strip, and uses repeat, lines, formatted, transform, indent and chars. It is compiled with --release 10 and 11.
public class Q11_Strings {
public static void main(String[] args) {
String input = " "; // spaces plus an em space
System.out.println("trim().isEmpty: " + input.trim().isEmpty() + " isBlank: " + input.isBlank());
String name = " asha \t";
System.out.println("[" + name.trim() + "] vs [" + name.strip() + "]");
System.out.println("[" + " x ".stripLeading() + "] [" + " x ".stripTrailing() + "]");
System.out.println("-".repeat(12));
"line one\nline two\r\nline three".lines().forEach(l -> System.out.println("> " + l));
System.out.println("order %d for %s".formatted(7, "ravi"));
System.out.println("a,b,,c,,".split(",").length + " parts (split drops trailing empties)");
String shout = "biryani".transform(s -> s.toUpperCase() + "!");
System.out.println(shout);
System.out.print("indented\nby four\n".indent(4));
System.out.println("chars: " + "raita".chars().filter(c -> c == 'a').count());
System.out.println(String.join("|", java.util.List.of("x", "y", "z")));
System.out.println(" padded".stripIndent() + " | " + "A\\tB".translateEscapes());
}
}Make the invisible visible: Compile proofs and run.
$ javac --release 10 Q11_Strings.java
Q11_Strings.java:4: error: cannot find symbol
System.out.println("trim().isEmpty: " + input.trim().isEmpty() + " isBlank: " + input.isBlank());
^
symbol: method isBlank()
location: variable input of type String
... (10 more errors trimmed)
$ javac --release 11 Q11_Strings.java
Q11_Strings.java:10: error: cannot find symbol
System.out.println("order %d for %s".formatted(7, "ravi"));
^
symbol: method formatted(int,String)
location: class String
... (4 more errors trimmed)
trim().isEmpty: false isBlank: true
[ asha] vs [asha]
[x ] [ x]
------------
> line one
> line two
> line three
order 7 for ravi
4 parts (split drops trailing empties)
BIRYANI!
indented
by four
chars: 2
x|y|z
padded | A BWhat you see: On release 10 the first error is isBlank(). On 11 the file still fails, but only at formatted, which is Java 15; this shows two different versions inside one file. In the run, trim().isEmpty() is false for the em space while isBlank() is true, and trim() leaves the em space in front of "asha" where strip() removes it.
Why: trim() is older than Unicode awareness in Java. It cleans ASCII spaces only, so user input pasted from a web page can slip through it.
Java 8
Helper code for common jobs.
s.trim().isEmpty()
String.join("", Collections.nCopies(
40, "-"))
String.format("order %d for %s", id, name)
s.split("\n")Java 11+
Methods on the string.
s.isBlank()
"-".repeat(40)
"order %d for %s".formatted(id, name)
s.lines()The shift: The common helpers moved from static utilities and loops onto the String itself.
Land it I use isBlank, strip, repeat, lines and formatted daily, and I remember that trim only knows ASCII whitespace.
- "What is the exact difference between trim and strip?"
-
trim()removes leading and trailing characters whose code is 32 or lower. That covers the ordinary space, tab, newline and carriage return, plus other control characters. It does not know about Unicode spaces.strip()usesCharacter.isWhitespace, which includes Unicode space separators except the non-breaking ones (the no-break space\u00A0is not counted as whitespace byisWhitespace). It removes the em space from the demo above.Two tiny surprises. First, the non-breaking space survives both
trim()andstrip(). If you scrape web text, a replace on\u00A0may still be needed. Second,isBlank()follows the same rules asstrip().My habit: use
strip()andisBlank()for any text from outside the program (forms, files, APIs). Keeptrim()only in code that must stay on Java 8. - "Why use lines() instead of split with a newline?"
-
split("\n")misses Windows line endings: a file with\r\nleaves a stray\rat the end of every line, which then breaks comparisons and prints oddly. It also drops trailing empty strings unless you pass a limit, which loses blank last lines silently. And it builds a whole array before you can use it.lines()recognises\n,\rand\r\nas separators, does not return a trailing empty line, and gives a lazyStream. That meanstext.lines().filter(...).map(...)reads naturally and processes line by line.For files,
Files.lines(path)is the streaming version that reads as it goes.Files.readString(path).lines()loads the file first, which is simpler for small files.The one thing
lines()does not do is keep empty lines at the end. If you must count them, usesplit("\n", -1)after normalising endings. - "Which String changes made a difference to performance or memory?"
-
The biggest change was not a method but an internal one in Java 9: compact strings. A string that contains only Latin-1 characters (most English, numbers and code) is stored one byte per character instead of two. For typical applications this cut string memory use by roughly a third to a half with no code change.
Java 9 also changed how
+concatenation is compiled. Instead of generatingStringBuildercode, the compiler emits aninvokedynamiccall, and the JVM chooses the fastest strategy at run time. That is why hand-writtenStringBuilderin a simple expression is no longer faster.Use
StringBuilderonly for loops that append many times. For one expression, plain+orformattedis fine.A trap from the other direction:
String.repeatandconcatcan allocate large arrays quickly, so repeating a long string a million times is still a memory problem. - "Is there a String method for padding or title case?"
-
No. Java has no
padLeftorcapitalizeinString. For padding, useString.format("%-10s", s)(left-aligned) or"%5d"for numbers, orformatted. For repeating a pad character:"0".repeat(5 - s.length()) + s.For capitalising, the usual one-liner is
Character.toUpperCase(s.charAt(0)) + s.substring(1), with an empty-string check. For full title case across words, use a library such as Apache Commons Text, because the rules (locale, small words) are not simple.What did arrive is
String.indentandtransform.transformis worth knowing because it lets a chain read left to right:"biryani".transform(s -> s.toUpperCase() + "!")instead of wrapping the string in a function call.If you do a lot of string work,
StringBuilderandString.join,Collectors.joiningcover most of what other languages build into the string type.
Q12. "List.of (9), Arrays.asList, Collections.unmodifiableList and Stream.toList() (16) — what is the difference in mutability?"
Reveal answer
Strong answer Five ways of getting a list give five different answers to "can I change it?", and the differences are the bug. List.of(...) is immutable: add, set and remove all throw UnsupportedOperationException, and it rejects null elements. Stream.toList() is also unmodifiable but allows nulls.
Arrays.asList(array) is fixed-size: you can set an element (and that writes through to the array), but add and remove throw. It is a window onto the array, not a copy.
Collections.unmodifiableList(list) is a read-only view. You cannot change it through the view, but if someone changes the original list, the view shows the change. It is a locked door on a room, not a copy of the room.
List.copyOf(list) (Java 10) is the real defensive copy: unmodifiable, independent of the source, and no nulls allowed. collect(Collectors.toList()) returns an ArrayList in practice, but its documentation promises nothing about mutability.
Rule of thumb: List.of for constants, List.copyOf to protect a field, new ArrayList<>(...) when you need to change it, and unmodifiableList only when you deliberately want a live read-only view.
Picture it A table made by probing each kind of list with a set and an add, then three traps: the view that follows its source, List.of(null), and asList writing through to an array.
The setup: Q12_Mutability.java builds each list and tries set(0, ...) and add(...), printing "ok" or "UOE" (UnsupportedOperationException). Then it changes a source list after wrapping it.
import java.util.*;
import java.util.stream.*;
public class Q12_Mutability {
static void probe(String name, List<String> list) {
String set = try_(() -> list.set(0, "changed"));
String add = try_(() -> list.add("extra"));
System.out.printf("%-26s set: %-5s add: %s%n", name, set, add);
}
static String try_(Runnable r) {
try { r.run(); return "ok"; } catch (UnsupportedOperationException e) { return "UOE"; }
}
public static void main(String[] args) {
probe("List.of", List.of("a", "b"));
probe("Arrays.asList", Arrays.asList("a", "b"));
probe("Collections.unmodifiable", Collections.unmodifiableList(new ArrayList<>(List.of("a", "b"))));
probe("Stream.toList()", Stream.of("a", "b").toList());
probe("collect(toList())", Stream.of("a", "b").collect(Collectors.toList()));
probe("List.copyOf", List.copyOf(new ArrayList<>(List.of("a", "b"))));
probe("new ArrayList<>(List.of)", new ArrayList<>(List.of("a", "b")));
var source = new ArrayList<>(List.of("a", "b"));
var view = Collections.unmodifiableList(source);
var copy = List.copyOf(source);
source.add("c");
System.out.println("view sees " + view + ", copy keeps " + copy);
try { List.of("a", null); } catch (NullPointerException e) { System.out.println("List.of(null) -> NPE"); }
System.out.println("Stream.toList() allows null: " + Stream.of("a", null).toList());
var backing = new String[] {"a", "b"};
Arrays.asList(backing).set(0, "z");
System.out.println("asList writes through to the array: " + backing[0]);
}
}Make the invisible visible: Compile proofs for 8, 9 and 16, then the run.
$ javac --release 8 Q12_Mutability.java
Q12_Mutability.java:14: error: cannot find symbol
probe("List.of", List.of("a", "b"));
^
symbol: method of(String,String)
location: interface List
... (11 more errors trimmed)
$ javac --release 9 Q12_Mutability.java
Q12_Mutability.java:17: error: cannot find symbol
probe("Stream.toList()", Stream.of("a", "b").toList());
^
symbol: method toList()
location: interface Stream<String>
... (6 more errors trimmed)
$ javac --release 16 Q12_Mutability.java
(compiles)
List.of set: UOE add: UOE
Arrays.asList set: ok add: UOE
Collections.unmodifiable set: UOE add: UOE
Stream.toList() set: UOE add: UOE
collect(toList()) set: ok add: ok
List.copyOf set: UOE add: UOE
new ArrayList<>(List.of) set: ok add: ok
view sees [a, b, c], copy keeps [a, b]
List.of(null) -> NPE
Stream.toList() allows null: [a, null]
asList writes through to the array: zWhat you see: List.of is not available on release 8, and Stream.toList() is not available on release 9; release 16 compiles everything. The table shows only Arrays.asList allows set but not add, collect(toList()) and the new ArrayList allow both, and everything else refuses both. The view printed [a, b, c] after the source grew, while the List.copyOf copy stayed [a, b].
Why: "Unmodifiable" does not mean "immutable". The view wrapper is read-only for you but not frozen for the original owner, which is why it fails as a defensive copy.
Java 8
Easy to leak a mutable list.
List<String> items = Arrays.asList(
"a", "b"); // set ok, add fails
return Collections.unmodifiableList(
internal); // view: still changesJava 10+
Say what you mean.
List<String> items = List.of("a", "b");
return List.copyOf(internal);
// need to change it?
var edit = new ArrayList<>(items);The shift: Each factory now names its behaviour: of for constants, copyOf for a protected snapshot.
Land it I use List.of for constants, List.copyOf to protect a field, and an unmodifiable view only when I want it to follow the source.
- "Why does List.of reject null, and is that a problem?"
-
The immutable collections were designed as value-like collections, and
nullinside a collection is the source of many bugs:contains(null)behaviour differs between implementations, andMap.ofusesnullinternally to mean "absent". Rejecting it at the door makes the whole family behave the same way, and it fails early with aNullPointerExceptionat the line that added thenull.It is a problem when you build a list from data that might contain null, such as a database column.
List.of(a, b, c)with a nullbcrashes right there. The fix is to filter first, or to useStream.toList(), which accepts nulls and lets you decide.The same applies to
Set.of,Map.ofandcopyOf.Set.of("a", "a")also throws, on duplicate elements;Map.ofon duplicate keys. Those are programming errors, not data errors.So the rule is: use
List.offor constants, where nulls are bugs. For external data useStream.toList()or a mutable list and clean it. - "What is the difference between an immutable list and an unmodifiable view?"
-
An immutable collection (
List.of,List.copyOf) has its own storage that nobody can ever change. If it contains immutable elements, it is truly frozen. An unmodifiable view (Collections.unmodifiableList) holds a reference to someone else's list and refuses changes made through itself, but it always shows the current state of the source.That has two consequences. A view is O(1) to create, while a copy is O(n). And a view is not safe to hand out as a snapshot: if the owner adds an item later, your reader sees it, and if the owner is another thread, the reader can see a half-updated list.
The JDK's own documentation calls the factory results "unmodifiable" and the covered ones "views", so the vocabulary is the same, but only
ofandcopyOfgive you what most people think of as immutable.When I return a field from a getter, I return
List.copyOf(field)if the list is small and rarely read, and keep an immutable list in the field if it is read often. A view is the third choice. - "Is Stream.toList() the same as List.of? Why did Java add it?"
-
Close, but not the same.
Stream.toList()returns an unmodifiable list likeList.of, but it allowsnullelements. It exists becausecollect(Collectors.toList())was long to write and promised nothing, and becauseCollectors.toUnmodifiableList()(Java 10) rejected nulls and was even longer to write.It is shorter, and because it can skip the intermediate
ArrayListwhen the stream knows its size, it can be a little faster. It is the default I use at the end of a pipeline when I do not need to change the result.What to remember:
toList()is allowed to contain null,toUnmodifiableList()is not, and the first one has been available only since Java 16. A library that supports Java 8 or 11 cannot use it.Question 43 compares
toList()withcollect(toList())in more detail, and question 52 lists which collectors give unmodifiable results. - "What is the right way to expose a collection from a class?"
-
Decide who owns the data, then pick one of three shapes. If callers only read, return an unmodifiable list. If the class changes the list later, return a copy (
List.copyOf(items)) so a caller's loop cannot be broken by a concurrent change. If you want to give a live read-only window, returnCollections.unmodifiableList(items)and document that it follows changes.Never return the internal mutable list. A caller who adds to it changes your object's state without calling your methods, so your checks (validation, events) never run. That is a defect that appears far from its cause.
A safer pattern is to hide the list entirely and offer methods:
addLine(Line l),lines()returning a copy,stream()for iteration. Records hold the same rule: copy lists in the compact constructor.For fields that you fill once, build the list with a builder or stream, then store the immutable result and return it as is, with no copy on each call.
Q13. "What did the Java 11 HttpClient replace, and what did Java 26 add to it?"
Reveal answer
Strong answer Before Java 11 the standard way to call an HTTP service was HttpURLConnection, an API from Java 1.1. It was blocking, awkward (you read status, headers and body through separate calls and streams), had no HTTP/2, and no async mode. Most teams used Apache HttpClient, OkHttp or Spring's RestTemplate instead.
Java 11 standardised java.net.http.HttpClient. It supports HTTP/1.1 and HTTP/2, synchronous calls (send) and asynchronous ones (sendAsync, returning a CompletableFuture), WebSocket, timeouts, redirects and a builder style. A client is thread-safe and meant to be created once and reused. The body is read through a BodyHandler, for example ofString(), ofFile(path) or ofInputStream().
Java 26 (March 2026) added HTTP/3 support (JEP 517), the version that runs over QUIC instead of TCP. It is opt-in: you ask for it on the builder with HttpClient.Version.HTTP_3. I could not run Java 26 on the course machine, so this part is from the release notes. A compile proof below shows the constant does not exist on JDK 25.
Which to use? For simple calls in tools and small services, the JDK client is enough and removes a dependency. For retry policies, connection tuning, interceptors and rich testing support, a library or Spring's RestClient is still more convenient.
Picture it A real HTTP server running inside the program serves a menu, and three clients call it: the new synchronous client, the new asynchronous client and the old HttpURLConnection.
The setup: Q13_Http.java starts the JDK's small built-in server on a free local port, so the demo runs offline. It then calls it three ways and prints the result.
import com.sun.net.httpserver.HttpServer;
import java.net.*;
import java.net.http.*;
import java.time.Duration;
import java.util.concurrent.*;
public class Q13_Http {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/menu", ex -> {
byte[] body = "{\"items\":[\"biryani\",\"dosa\"]}".getBytes();
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
String url = "http://127.0.0.1:" + server.getAddress().getPort() + "/menu";
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2)).build(); // reusable, thread-safe
HttpRequest req = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(2)).GET().build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("sync : " + res.statusCode() + " " + res.body() + " via " + res.version());
CompletableFuture<String> async = client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body);
System.out.println("async: " + async.get(2, TimeUnit.SECONDS));
HttpURLConnection old = (HttpURLConnection) URI.create(url).toURL().openConnection(); // pre-11 style
try (var in = old.getInputStream()) {
System.out.println("old : " + old.getResponseCode() + " " + new String(in.readAllBytes()));
}
server.stop(0);
}
}Make the invisible visible: Run, then compile with 10 and 11, then try HTTP/3 on JDK 25.
sync : 200 {"items":["biryani","dosa"]} via HTTP_1_1
async: {"items":["biryani","dosa"]}
old : 200 {"items":["biryani","dosa"]}
$ javac --release 10 Q13_Http.java
Q13_Http.java:3: error: package java.net.http does not exist
import java.net.http.*;
^
... (8 more errors trimmed)
$ javac --release 11 Q13_Http.java
(compiles)
$ javac --release 25 Q13_Http3.java
Q13_Http3.java:5: error: cannot find symbol
System.out.println(HttpClient.Version.HTTP_3); // added in Java 26 (JEP 517)
^
symbol: variable HTTP_3
location: class Version
openjdk version "25.0.5.1" 2026-11-17What you see: All three clients got the same JSON. The protocol shown for the new client is HTTP_1_1 because the tiny built-in server speaks only HTTP/1.1 and the address is plain http://. Release 10 has no java.net.http package; release 11 compiles it. On JDK 25, HttpClient.Version.HTTP_3 is "cannot find symbol", so it truly is newer than 25.
Why: The new client's builder, request and handler make timeouts and async explicit. With the old connection you manage streams and status codes by hand.
Java 8
A connection object and streams.
URL u = new URL(url);
HttpURLConnection c =
(HttpURLConnection) u.openConnection();
c.setConnectTimeout(2000);
int code = c.getResponseCode();
try (InputStream in = c.getInputStream()) {
body = new String(in.readAllBytes());
}Java 11
Build, send, read the body.
var client = HttpClient.newHttpClient();
var req = HttpRequest.newBuilder(
URI.create(url)).build();
var res = client.send(req,
BodyHandlers.ofString());
int code = res.statusCode();
String body = res.body();The shift: One reusable client, an immutable request, and a handler that says how to read the body.
Land it Java 11 standardised a modern HTTP client with HTTP/2 and async calls, and Java 26 added HTTP/3 as an opt-in.
- "Is the JDK HttpClient good enough, or should I use something else?"
-
For plain calls to a handful of services, yes. It supports connection reuse, HTTP/2, timeouts and async, and it costs no dependency. For scripts, tests and command-line tools it is the first choice.
For a production service that calls many downstream systems, features around the client matter more than the client: retries with backoff, circuit breakers, metrics, connection pool limits, request logging, and easy mocking in tests. Spring's
RestClient(Spring 6.1+) andWebClient, OkHttp and Apache HttpClient give you those or integrate with libraries that do.One weak spot of the JDK client: you cannot easily configure the connection pool size, and error messages for TLS problems are terse. Many teams hit that and move to a library.
My rule: start with the JDK client, switch when I need retries, pooling control or observability that I would otherwise write myself.
- "Why does the demo show HTTP/1.1 and not HTTP/2?"
-
HTTP/2 is normally negotiated over TLS using a TLS extension called ALPN, so the client and server agree during the secure handshake. Over plain
http://, the client has to try an upgrade request, and the tiny built-in server in the demo only speaks HTTP/1.1, so the answer is HTTP/1.1.The builder's default is to prefer HTTP/2 and fall back, which is the right default for real services. You can force HTTP/1.1 with
HttpClient.newBuilder().version(HTTP_1_1)when a proxy or an old server misbehaves.To see HTTP/2 you need a server that supports it over TLS, for instance a public site. That cannot run offline, so this chapter's demo stays local.
The same ideas apply to HTTP/3 in Java 26: it will also need a server that supports it (and UDP reachable through your network), and it will fall back when it cannot connect. Check the Java 26 documentation for the exact builder options.
- "How do I do async calls and timeouts with it?"
-
sendAsync(request, handler)returns aCompletableFuture<HttpResponse<T>>. You attach steps withthenApplyandthenCombineand the call does not block your thread. The demo's second line does exactly this:sendAsync(...).thenApply(HttpResponse::body).There are two timeouts and they do different things.
HttpClient.Builder.connectTimeoutlimits only how long connecting may take.HttpRequest.Builder.timeoutlimits the time until the response headers arrive, and it throwsHttpTimeoutException. Neither limits how long reading a big body takes, so for a total deadline wrap the future withorTimeout.The default executor for async callbacks is an internal one. You can pass your own with
HttpClient.newBuilder().executor(...), for example a virtual-thread executor.The CompletableFuture chapters (#completable) show how to combine several calls with a fallback.
- "What are the migration traps from HttpURLConnection?"
-
Three bite regularly. First,
HttpURLConnectionfollows redirects by default, but only within the same protocol; the new client does not follow redirects unless you setfollowRedirects(NORMAL). Second, error status codes: the old class threw anIOExceptionon 4xx and 5xx when you read the body; the new one returns a normal response with a status code, and you check it yourself.Third, the new client sets some headers for you, and some headers are restricted (
Host,Content-Length,Connection) and cannot be set manually.Also,
HttpClientinstances own threads and connections, so create one and share it. In Java 21 it implementsAutoCloseable, so a short-lived one can be closed with try-with-resources.A migration plan I use: wrap the old calls behind a small interface, write the new implementation, run both against a test server and compare status, headers and body before switching.
Q14. "Helpful NullPointerExceptions (14): what does the message tell you now that it did not before?"
Reveal answer
Strong answer Before Java 14, a NullPointerException had no message. The stack trace gave a line number, and if that line was orders.get(7).customer().address().city().length(), you had to guess which of five calls returned null. You added logging or ran it in a debugger.
Since Java 14 the JVM describes what failed and why. For example:
# illustrative
Cannot invoke "Address.city()" because the return value of "Customer.address()" is nullThe message names the method you tried to call and the expression that was null. Java 14 introduced it behind a flag (-XX:+ShowCodeDetailsInExceptionMessages) and Java 15 turned it on by default.
It is computed only when the exception message is first asked for, so there is no run-time cost on the hot path. The JVM works backwards from the failing bytecode to describe the value.
One limit: local variable names appear only if the class was compiled with -g (debug info). Otherwise you see "<local2>" as the course machine did. Maven and Gradle normally compile with debug info on, so you get real names in applications.
Caution: the message can include method and field names. If you log it, the text is helpful for you, and the same text should not be sent to clients in an API error body.
Picture it The same three null mistakes on JDK 8 and on newer JDKs, plus the flag that turns the feature off.
The setup: Q14_Npe.java triggers three NPEs: a chain of calls, a missing map entry and a null array element. The old version (Q14_NpeOld.java, plain classes) is compiled and run with JDK 8. The new one runs on JDK 17 and 25.
import java.util.*;
public class Q14_Npe {
record Address(String city) {}
record Customer(String name, Address address) {}
record Order(int id, Customer customer) {}
public static void main(String[] args) {
Map<Integer, Order> orders = new HashMap<>();
orders.put(7, new Order(7, new Customer("asha", null)));
try {
System.out.println(orders.get(7).customer().address().city().length());
} catch (NullPointerException e) { System.out.println("A: " + e.getMessage()); }
try {
System.out.println(orders.get(99).customer().name());
} catch (NullPointerException e) { System.out.println("B: " + e.getMessage()); }
String[] names = new String[2];
try {
System.out.println(names[1].trim());
} catch (NullPointerException e) { System.out.println("C: " + e.getMessage()); }
}
}Make the invisible visible: JDK 8, JDK 17, JDK 25, the switch-off flag, and a build with -g.
$ JDK 8: java Q14_NpeOld
A: null
B: null
C: null
$ JDK 17: java Q14_Npe
A: Cannot invoke "Q14_Npe$Address.city()" because the return value of "Q14_Npe$Customer.address()" is null
B: Cannot invoke "Q14_Npe$Order.customer()" because the return value of "java.util.Map.get(Object)" is null
C: Cannot invoke "String.trim()" because "<local2>[1]" is null
$ JDK 25: java Q14_Npe
A: Cannot invoke "Q14_Npe$Address.city()" because the return value of "Q14_Npe$Customer.address()" is null
B: Cannot invoke "Q14_Npe$Order.customer()" because the return value of "java.util.Map.get(Object)" is null
C: Cannot invoke "String.trim()" because "<local2>[1]" is null
$ JDK 25: java -XX:-ShowCodeDetailsInExceptionMessages Q14_Npe
A: null
B: null
C: null
$ javac -g Q14_Npe.java && java Q14_Npe # keep local variable names
C: Cannot invoke "String.trim()" because "names[1]" is nullWhat you see: JDK 8 prints null three times. JDK 17 and 25 name the failing call and the null expression. With the flag off, 25 goes back to null. With -g, case C says "names[1]" instead of "<local2>[1]".
Why: The JVM can read the bytecode around the failure. It sees "load local 2, load element 1, call trim" and describes that, so no source file is needed.
Java 8 message
Which part was null?
Exception in thread "main"
java.lang.NullPointerException
at Main.main(Main.java:12)
// line 12 has five method callsJava 15+ message
The failing part is named.
java.lang.NullPointerException:
Cannot invoke "Address.city()" because
the return value of "Customer.address()"
is null
at Main.main(Main.java:12)The shift: The line number told you where; the message now tells you which part of the line.
Land it Since Java 15 a NullPointerException names the call that failed and the expression that was null, with no code change.
- "Is there a cost, and can I turn it off?"
-
The cost is only paid when the exception is created and its message is read, not on the normal path. The JVM builds the text by analysing the bytecode at the failing instruction, which takes microseconds. If your code throws millions of NPEs in a loop, which it should not, you would see that.
You can turn it off with
-XX:-ShowCodeDetailsInExceptionMessages, as the last-but-one run above shows. The usual reason is a security rule: the message can reveal method and variable names that you do not want in logs seen by outsiders.The message is not part of the exception's stable API. Do not parse it, and do not compare it in tests. Its wording could change between releases.
My advice: leave it on, and keep API error responses generic (a status and a code) while the details go to the server log.
- "Does it work for fields, arrays and unboxing?"
-
Yes, for all of them. If you read a field of a null object the message says
Cannot read field "name" because "c" is null. For arrays it saysCannot load from object array because "names" is nullorCannot read the array length. For unboxing it says this:the unboxing messageruns offlineCannot invoke "java.lang.Integer.intValue()" because ... is nullwhich tells you that a
null Integerwas unboxed into anint.That last one is the most common hidden NPE. A
Map<String, Integer>lookup assigned to anintvariable throws when the key is missing, and the old message gave no hint. Now the message namesInteger.intValue().The same works for synchronized blocks on a null lock,
throw null, and enhancedforover a null collection.The one thing it cannot describe is an expression it cannot name, such as a lambda parameter without debug info: you then get
"<local4>"style names. - "Should I still add null checks or Objects.requireNonNull?"
-
Yes, but for a different reason. The helpful message tells you where a null reached a call. It does not tell you where it came from. A null stored in a field three calls earlier still fails at the later line.
Objects.requireNonNull(x, "customer")at the boundary of a constructor or public method fails early, at the line that received the bad value, with a message you wrote. That is a better place for the failure.The helpful NPE text has made some old defensive checks unnecessary, such as a check that exists only to give a better message. Delete those when you find them. Keep the ones that protect invariants.
And prefer designs where null cannot arrive:
Optionalreturn types, records that validate in the constructor, and collections that are never null (return empty lists, not null). - "What do I need to do to get local variable names in the message?"
-
Compile with debug information for local variables:
javac -g(or-g:vars). Without it the class file has no table of variable names, and the JVM can only say"<local2>", the slot number.Maven's compiler plugin and Gradle's Java plugin both include debug information by default for the standard build, so deployed applications usually show real names. The single-file source launcher (
java Q14_Npe.java) does not add-g, which is why the demo's first runs show<local2>.Field and method names always appear, because they are part of the class file's structure. Parameter names appear only with
-parametersor-g.If a production jar was built without debug info, you still get most of the value from calls and fields. For deep chains, that is usually enough.
Q15. "Compact source files and instance main methods (25): what can a beginner write now?"
Reveal answer
Strong answer Until Java 24, the smallest runnable program needed a public class, a public static void main(String[] args) method and System.out.println. A beginner had to type about five concepts (class, public, static, void, String array) before seeing "hello" on the screen, and none of them could be explained yet.
Java 25 (JEP 512, final) removes that. A file can contain just void main() { IO.println("hello"); }. Three changes make this work. A compact source file may hold methods and fields at the top level; the compiler wraps them in an implicit class named after the file. An instance main method may be non-static, without public and without the String[] parameter. And IO.println, IO.print and IO.readln are simple console helpers in java.lang, so no import is needed.
The launch protocol picks the best main it finds: a static one with arguments first, then others. It then creates an instance if needed and calls it. Everything old still works. This is an addition, not a replacement.
It is built for learning and for small scripts. Real applications still use named classes, packages and often a framework. The first version appeared as a preview in 21 under the name "unnamed classes", was reshaped in 22, 23 and 24, and became final in 25.
It combines well with the Java 11 single-file launcher: java Hello.java compiles and runs the file in one step.
Picture it A seven-line file with a helper method runs directly, and the same file is refused on release 24.
The setup: Q15_Hello.java has no class declaration at all: a main method, a second method orders(), and IO.println for output.
void main() {
IO.println("hello from a compact source file");
IO.println("orders today: " + orders());
}
int orders() { return 12; }Make the invisible visible: Run it directly, then compile it with 24 and 25.
hello from a compact source file
orders today: 12
$ javac --release 24 Q15_Hello.java
Q15_Hello.java:1: error: implicitly declared classes are not supported in -source 24
void main() {
^
(use -source 25 or higher to enable implicitly declared classes)
$ javac --release 25 Q15_Hello.java
(compiles)What you see: The program ran with java Q15_Hello.java. On release 24 the compiler says "implicitly declared classes are not supported in -source 24", and on 25 it compiles. The old and new forms behave identically at run time.
Why: The compiler quietly made a class called Q15_Hello, put both methods into it, and instantiated it. Nothing changed in the bytecode model, only in how much you must type.
Java 24
Ceremony before output.
public class Hello {
public static void main(String[] args) {
System.out.println("hello");
}
}Java 25
The point, and nothing else.
void main() {
IO.println("hello");
}The shift: A beginner meets class, static and arrays when they need them, not on day one.
Land it Java 25 lets a file be just methods with a main that needs no class, static or arguments, which makes small programs and teaching much lighter.
- "Does this change how real applications are written?"
-
Not really. A service with packages, many classes and a framework still declares classes the normal way, and Spring Boot's
mainstays as it is. The feature targets two groups: beginners, and people who write small scripts or tools.For scripts, though, it is a real change. A 20-line utility to reformat a CSV can now be one file with a few methods, started with
java Tool.java, with no build tool and no class wrapper. Together withimport module java.base;(question 16) the top of the file is also short.The design rule is "grow without rewriting": when the file gets big, you wrap the methods in a class by hand and nothing else needs to change.
For team code I keep the explicit class. It gives the file a name that other classes can use, which a compact source file cannot offer, because its implicit class cannot be referenced from other files.
- "What are the rules for the main method now?"
-
The launcher looks for a method named
mainand chooses in this order. First:static void main(String[] args), the classic one. Second:static void main(). Third: an instancevoid main(String[] args). Fourth: an instancevoid main(). A non-public or package-private one is fine.For an instance main, the class needs a non-private constructor with no parameters, because the launcher creates the object first. If that is missing, the launch fails with a clear error.
Both static and instance mains in the same class are legal. The static, argument-taking one wins, which keeps all existing programs working exactly as before.
The return type must still be
void. And a compact source file must contain amain, or it cannot be launched. - "What is IO, and why not System.out?"
-
IOis a new class injava.langwith a few static methods for the console:IO.print,IO.printlnandIO.readln(prompt). It exists so a beginner can read a line from the keyboard without learningScannerorBufferedReader. They are thin wrappers overSystem.outandSystem.in, using the console's charset.You write
IO.println(...)with the class name, and it works in any file with no import, becausejava.langis always imported. A bareprintln(...)does not compile (checked on JDK 25). To drop the prefix, addimport static java.lang.IO.*;.System.out.printlnis not deprecated and still works everywhere. In real services you use a logger anyway.IOis for the prompt and the first-day programs.A detail to check in the Javadoc before you write an input loop: what
IO.readlnreturns when the input ends. - "How is a compact source file different from the Java 11 single-file launch?"
-
They are two separate features that work well together. The Java 11 feature is about how you run a file:
java Hello.javacompiles in memory and starts it, with no.classfile on disk. The file still had to declare a class with a staticmain.The Java 25 feature is about what the file may contain: methods and fields without a class around them, and a simpler
main. You can compile such a file withjavacas well, and you get a class named after the file.Java 22 extended the launcher to multi-file programs: the launcher compiles other source files it finds next to the main one. The demos in this chapter's
Efolder rely on that:Data.java,Order.javaandLine.javaare found automatically.So a complete small program today can be a few files in a folder and one command, with no build tool at all.
Q16. "Flexible constructor bodies and module import declarations (both final in 25): what do they allow?"
Reveal answer
Strong answer Flexible constructor bodies (JEP 513) let a constructor run statements before it calls super(...) or this(...). Until Java 24 the call to super had to be the very first statement. So a subclass that wanted to check or tidy an argument before passing it up had to do it inside the call: super(validate(name)) with a static helper method, or build the arguments in an awkward way.
Now you can write a check, compute a local variable and then call super(clean). The restriction that remains is that, before super(), you may not use this: you cannot read instance fields or call instance methods, because the object is not built yet. You can, however, assign to fields of your own class before super() (useful when the superclass constructor calls an overridden method that reads those fields).
Module import declarations (JEP 511) let one line import everything a module exports: import module java.base;. That covers java.util, java.io, java.nio.file, java.util.stream and more, so a small program no longer needs a wall of import lines.
Name clashes are possible: java.sql.Date and java.util.Date both exist, and importing both modules makes the simple name Date ambiguous. An explicit single-type import wins over a module import, which settles it.
Both were preview features in earlier releases (flexible constructors from 22, module imports from 23) and became final in 25.
Picture it A constructor that validates before super(...) and a program with no imports except one module line.
The setup: Q16_Flexible.java uses import module java.base;, and a PricedItem constructor that throws on a negative price and strips the name before it calls super(clean). A tiny file Q16_Ctor.java isolates the constructor feature.
import module java.base;
public class Q16_Flexible {
static class Item {
final String name;
Item(String name) { this.name = name; }
}
static class PricedItem extends Item {
final int priceCents;
PricedItem(String name, int priceCents) {
if (priceCents < 0) throw new IllegalArgumentException("price < 0: " + priceCents); // runs BEFORE super(...)
var clean = name.strip().toLowerCase(); // local variables are fine too
super(clean);
this.priceCents = priceCents;
}
}
public static void main(String[] args) {
var p = new PricedItem(" Biryani ", 24900);
System.out.println(p.name + " " + p.priceCents);
try { new PricedItem("x", -1); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
List<String> l = new ArrayList<>(List.of("b", "a")); // no import java.util.* needed
Collections.sort(l);
System.out.println(l + " " + Stream.of(1, 2, 3).map(i -> i * 2).toList());
}
}Make the invisible visible: Run it, then compile both files with 24 and 25.
biryani 24900
price < 0: -1
[a, b] [2, 4, 6]
$ javac --release 24 Q16_Flexible.java
Q16_Flexible.java:1: error: module imports are not supported in -source 24
import module java.base;
^
(use -source 25 or higher to enable module imports)
$ javac --release 25 Q16_Flexible.java
(compiles)
$ javac --release 24 Q16_Ctor.java
Q16_Ctor.java:6: error: flexible constructors is not supported in -source 24
super(name.strip());
^
(use -source 25 or higher to enable flexible constructors)
$ javac --release 25 Q16_Ctor.java
(compiles)
xWhat you see: The program ran. On release 24, the module import is rejected first ("module imports are not supported in -source 24") and the isolated constructor file fails with "flexible constructors is not supported in -source 24". On release 25 both compile.
Why: The constructor check runs before the superclass is built, so a bad price never creates a half-initialised object. And the program used List, ArrayList, Collections and Stream with a single import line.
Java 24
A static helper inside super.
Priced(String name, int cents) {
super(check(name, cents));
this.cents = cents;
}
static String check(String n, int c) {
if (c < 0) throw new IllegalArgumentException();
return n.strip();
}Java 25
Plain statements first.
Priced(String name, int cents) {
if (cents < 0)
throw new IllegalArgumentException();
var clean = name.strip();
super(clean);
this.cents = cents;
}The shift: Validation reads in the order you think about it, and no helper is needed just to get a value into super.
Land it Flexible constructors let me validate before calling super, and a module import replaces a wall of import lines with one.
- "What can I NOT do before super()?"
-
You cannot refer to the object under construction. That means no reading or calling anything through
this: no instance fields, no instance methods, nothispassed to another method. The compiler rejects them, because the superclass has not run yet and the object does not exist in a valid state.You can use the constructor's parameters, local variables, static methods and static fields, and you can assign to fields declared in your own class. That last rule solves an old trap: a superclass constructor that calls an overridden method which reads a subclass field would see zero or null. Now you can set the field before
super()runs.You also cannot return from the constructor before the call, and you cannot call
superin a branch only. The call must happen exactly once on every path.In short, the early part is a "prologue" that prepares arguments. It must not depend on the object itself.
- "Is import module the same as import java.base.*?"
-
It is similar to importing every package that the module exports, but you write one line and it follows the module as the JDK changes.
import module java.base;makes all types injava.util,java.io,java.math,java.nio.*,java.time,java.util.concurrent,java.util.functionandjava.util.streamavailable by simple name.It also pulls in packages exported by modules that the named module "requires transitively". For
java.basethat is nothing extra, but forjava.seit is a big set includingjava.sqlandjava.xml.The costs are readability and ambiguity. A reader no longer sees where a class came from, and two packages with the same simple name can clash (
java.util.Listandjava.awt.List). The compiler reports it when you use the ambiguous name, and a single-type import fixes it.My preference: use it in scripts and tutorials, keep explicit imports in production code, where tools like import-order checks and code review depend on them.
- "Why is the call to super allowed to appear later, and is this unsafe?"
-
The old rule, "super first", was a blunt way to guarantee that no code runs on a half-built object. The new rule keeps the guarantee but states it exactly: code before
super()may not touch the object. The compiler enforces that, so the protection is the same and the awkwardness is gone.The earlier workaround was a static helper method inside the
super(...)call, or a private constructor chain. Both work, but both hide the intent. Validation that reads top to bottom is easier to review.There is one subtle new power. Because you can assign your own fields before
super(), a superclass that calls an overridden method from its constructor now sees initialised data. That fixes a long-standing source of bugs in class hierarchies, although the better answer is still not to call overridable methods from constructors.The feature went through three previews (22, 23 and 24) to settle on those exact rules.
- "Does this change records or enums?"
-
Records have their own rules: a canonical constructor must still assign every field, and a record cannot call
super, because it always extendsjava.lang.Record. The compact constructor remains the right place for validation in a record.Enums do not extend by
supereither. So the feature matters only for ordinary class hierarchies, such as an abstractNotificationwithEmailNotificationandSmsNotificationsubclasses that clean their arguments before the common constructor.For most code the visible change is small, one or two constructors per project that used to need a static helper, but it removes a constant source of "why can I not just write an if here" questions from new Java developers.
Q17. "Scoped values (final in 25) versus ThreadLocal — what is the difference?"
Reveal answer
Strong answer Both give code a value that is "ambient": available deep in a call chain without passing it through every parameter. A typical use is the request id, the logged-in user or a transaction. They differ in how long the value lives and who can change it.
A ThreadLocal is a variable with one slot per thread. You call set and the value stays until someone calls remove or the thread dies. It is mutable: any code on the thread can overwrite it. On a pooled thread it outlives the request unless you remember to clear it, which is a classic leak and a classic source of "request A saw request B's user". Child threads can inherit a copy, which costs memory when you have many.
A ScopedValue is bound for the duration of one piece of code: ScopedValue.where(REQUEST_ID, "req-42").run(() -> ...). Inside the lambda, REQUEST_ID.get() returns it. When the lambda ends, the binding disappears automatically. It is immutable inside the scope. A nested where can rebind it for a smaller scope, and when that ends the outer value returns.
The result is cleaner life-cycle (no cleanup code), safer sharing (no one can change it under you), and much lower cost with virtual threads, because a scoped value is not copied per thread. Scoped values were previewed from 20 and became final in 25.
Use ScopedValue for new code that passes context down a call tree. Keep ThreadLocal where a framework needs it or where the value truly changes during the thread's life.
Picture it A request id passed through nested calls with a scoped value, then a thread-local that leaks to the next request on a pooled thread.
The setup: Q17_Scoped.java binds REQUEST_ID to "req-42", calls a method two levels deep, rebinds to "req-43" in an inner scope, and checks the value after the scope ends. Then it sets a ThreadLocal in one task on a one-thread pool and reads it in the next task.
import java.util.concurrent.*;
public class Q17_Scoped {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static final ThreadLocal<String> TL = new ThreadLocal<>();
static void deep() { System.out.println(" deep sees scoped=" + (REQUEST_ID.isBound() ? REQUEST_ID.get() : "unbound")
+ " threadlocal=" + TL.get()); }
public static void main(String[] args) throws Exception {
System.out.println("before: bound? " + REQUEST_ID.isBound());
ScopedValue.where(REQUEST_ID, "req-42").run(() -> {
deep();
ScopedValue.where(REQUEST_ID, "req-43").run(Q17_Scoped::deep); // nested rebinding
deep(); // back to req-42
});
System.out.println("after : bound? " + REQUEST_ID.isBound());
// ThreadLocal on a pool thread: the value outlives the request unless someone remembers to remove it
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(() -> TL.set("req-1 (never removed)")).get();
pool.submit(() -> System.out.println("next request on same thread sees threadlocal: " + TL.get())).get();
pool.shutdown();
// a scoped value is visible in a thread started by a StructuredTaskScope, not in a plain Thread
Thread t = new Thread(() -> System.out.println("plain thread bound? " + REQUEST_ID.isBound()));
ScopedValue.where(REQUEST_ID, "req-9").run(() -> { t.start(); try { t.join(); } catch (InterruptedException e) {} });
}
}Make the invisible visible: Run it, then compile with release 24.
before: bound? false
deep sees scoped=req-42 threadlocal=null
deep sees scoped=req-43 threadlocal=null
deep sees scoped=req-42 threadlocal=null
after : bound? false
next request on same thread sees threadlocal: req-1 (never removed)
plain thread bound? false
$ javac --release 24 Q17_Scoped.java
Q17_Scoped.java:4: error: ScopedValue is a preview API and is disabled by default.
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
^
(use --enable-preview to enable preview APIs)
Q17_Scoped.java:4: error: ScopedValue is a preview API and is disabled by default.
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
^
(use --enable-preview to enable preview APIs)
... (3 more errors trimmed)What you see: The scoped value was req-42, then req-43 in the nested scope, then back to req-42, and unbound after the scope. The ThreadLocal shows the leak: the second task on the same pooled thread still sees req-1 (never removed). A plain new Thread started inside the scope is not bound. On release 24, ScopedValue is still a preview API and the compile fails.
Why: The scoped binding is tied to the code block, not to the thread. That is why it cannot leak to a later request and why it does not need cleanup.
ThreadLocal
Set, use, and remember to remove.
static final ThreadLocal<String> ID =
new ThreadLocal<>();
ID.set("req-42");
try {
handle(); // reads ID.get()
} finally {
ID.remove(); // easy to forget
}ScopedValue
Bound for the block only.
static final ScopedValue<String> ID =
ScopedValue.newInstance();
ScopedValue.where(ID, "req-42")
.run(() -> handle()); // reads ID.get()
// binding ends by itselfThe shift: The value's lifetime is the lifetime of the code block, so there is nothing to clean up.
Land it A scoped value is an immutable binding that lasts exactly as long as a block of code, while a ThreadLocal is a mutable per-thread slot you must clean up yourself.
- "Why are scoped values better with virtual threads?"
-
A virtual thread is cheap, so a program may create a million of them. A
ThreadLocalallocates a map entry per thread and, withInheritableThreadLocal, copies the parent's values to each child. With a million threads that is a million copies and a lot of memory.A scoped value is stored as a binding that child scopes inherit by reference. Structured concurrency (question 99) forwards the bindings to its forked threads without copying. So the cost does not grow with the number of threads.
There is also a design point. Virtual threads are meant to be created per task and thrown away, never pooled. A
ThreadLocalas a per-thread cache therefore stops making sense, because each thread lives for one task. Scoped values fit the "one task, one scope" model.That does not make
ThreadLocalwrong on virtual threads, only wasteful when used as a cache. Question 98 goes deeper. - "Can I change a scoped value?"
-
No, not inside the scope where it is bound. There is no
set. You can only bind a new value for a nested scope with anotherwhere(...), as the demo does withreq-43. When the inner scope ends, the outer value is visible again.That is a deliberate restriction. With a
ThreadLocal, any code deep in the stack can overwrite the value, and the code above has no idea. With a scoped value, a caller's value cannot change under its feet, so reasoning about it is easier.If you need mutable shared state, bind a mutable object (an
AtomicIntegeror a request context object) and mutate that. The binding is fixed but the object it points to may change, and you take responsibility for thread-safety.For most "ambient context" uses (request id, user, locale), you never need to change the value, which is why the restriction costs so little.
- "Are scoped values inherited by child threads?"
-
Not by plain threads. In the demo, a thread created with
new Threadinside the scope printedplain thread bound? false. A scoped value is visible only in code that runs inside the scope, on the same thread.Threads created through structured concurrency (
StructuredTaskScope, which is still a preview in 25) are different. The scope forks its subtasks as children and passes the current bindings on to them, so context follows the work as it fans out, and ends when the scope closes.That is the intended pairing: scoped values carry context down, and structured concurrency makes sure the child threads cannot outlive the parent scope.
If you need the value in a thread pool task, you capture it before submitting: read the value, then pass it as a parameter or rebind it inside the task with
where(...). - "Should I migrate existing ThreadLocal code?"
-
Not as a project. Migrate where the pain is: places with remove-in-finally boilerplate, places that leaked a value to a later request, or hot paths on virtual threads where copying costs show up in profiles.
Many frameworks use
ThreadLocalinternally. Spring'sSecurityContextHolder,RequestContextHolderand logging MDC (mapped diagnostic context) all use it. You cannot switch those yourself, and they will move at their own pace. Libraries that run on Java 21 or earlier cannot useScopedValueyet, since it is final only in 25.For new code on Java 25 with a call tree you control, I use scoped values. For older targets or when I am inside a framework's own context, I follow what the framework uses and clean up carefully.
A practical safety net in the meantime: wrap every
ThreadLocal.setin a try-finally withremove, or put it behind a small helper that does so.
Q18. "Stream gatherers (final in 24): what can you do that collectors could not?"
Reveal answer
Strong answer A stream has two kinds of end. A collector sits at the end of a pipeline and turns all the elements into one result (a list, a map, a sum). Between the source and the end, you had only a fixed menu of intermediate operations: map, filter, flatMap, distinct, sorted, limit and a few more. If you needed something else in the middle, you could not add it.
A gatherer (Java 24, final) is a custom intermediate operation, used with stream.gather(...). It can keep state between elements, emit zero, one or many outputs per input, look at groups of neighbours, and even stop the stream early. The standard library ships ready-made ones in java.util.stream.Gatherers: windowFixed(n) (chunks of n), windowSliding(n) (overlapping windows), scan (running totals), fold (reduce into one value as a stage) and mapConcurrent(max, fn) (map with up to max calls in flight at once, output order kept).
What you could not do before without ugly tricks: moving averages, running totals as a stream stage, "remove consecutive duplicates", "group into batches of 100 for a bulk insert", and "call a slow service for each element, ten at a time". Each of those needed a loop or a hand-made iterator.
Gatherers can run in parallel if you give them a combiner. The built-in mapConcurrent uses virtual threads to do its concurrent work.
They were previewed in 22 and 23 and became final in 24. Release 23 refuses them without --enable-preview, as the proof below shows.
Picture it Seven days of revenue run through the standard gatherers, followed by a gatherer written in nine lines.
The setup: Q18_Gatherers.java applies windowFixed(3), windowSliding(3) (turned into a moving average), scan (running total), fold and mapConcurrent(4, ...) over eight 100 ms fake rider lookups. At the end, Gatherer.ofSequential builds "drop consecutive duplicates".
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.*;
public class Q18_Gatherers {
public static void main(String[] args) {
List<Integer> daily = List.of(54700, 29700, 61300, 48800, 52100, 70300, 39900); // revenue per day, rupees
System.out.println("windowFixed(3) : " + daily.stream().gather(Gatherers.windowFixed(3)).toList());
System.out.println("windowSliding(3): " + daily.stream().gather(Gatherers.windowSliding(3))
.map(w -> w.stream().mapToInt(i -> i).sum() / 3).toList());
System.out.println("scan (running) : " + daily.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
System.out.println("fold (one value): " + daily.stream().gather(Gatherers.fold(() -> 0, Integer::sum)).toList());
var inFlight = new AtomicInteger(); var peak = new AtomicInteger();
long t0 = System.nanoTime();
List<String> eta = IntStream.rangeClosed(1, 8).boxed()
.gather(Gatherers.mapConcurrent(4, id -> {
peak.accumulateAndGet(inFlight.incrementAndGet(), Math::max);
try { Thread.sleep(100); } catch (InterruptedException e) {}
inFlight.decrementAndGet();
return "rider" + id;
})).toList();
System.out.println("mapConcurrent(4): " + eta + " peak in flight=" + peak
+ " in " + (System.nanoTime() - t0) / 1_000_000 + " ms");
// your own gatherer: drop CONSECUTIVE duplicates, keeping state between elements
Gatherer<String, ?, String> dedupe = Gatherer.ofSequential(
() -> new String[1],
(last, item, downstream) -> {
if (item.equals(last[0])) return true; // skip, keep going
last[0] = item;
return downstream.push(item);
});
System.out.println("custom gatherer : " + Stream.of("PLACED", "PLACED", "COOKING", "COOKING", "PLACED")
.gather(dedupe).toList());
}
}Make the invisible visible: Run it, then compile with 23 and 24.
windowFixed(3) : [[54700, 29700, 61300], [48800, 52100, 70300], [39900]]
windowSliding(3): [48566, 46600, 54066, 57066, 54100]
scan (running) : [54700, 84400, 145700, 194500, 246600, 316900, 356800]
fold (one value): [356800]
mapConcurrent(4): [rider1, rider2, rider3, rider4, rider5, rider6, rider7, rider8] peak in flight=4 in 231 ms
custom gatherer : [PLACED, COOKING, PLACED]
$ javac --release 23 Q18_Gatherers.java
Q18_Gatherers.java:8: error: Gatherers is a preview API and is disabled by default.
System.out.println("windowFixed(3) : " + daily.stream().gather(Gatherers.windowFixed(3)).toList());
^
(use --enable-preview to enable preview APIs)
Q18_Gatherers.java:8: error: <R>gather(Gatherer<? super T,?,R>) is a preview API and is disabled by default.
System.out.println("windowFixed(3) : " + daily.stream().gather(Gatherers.windowFixed(3)).toList());
^
(use --enable-preview to enable preview APIs)
where R,T are type-variables:
R extends Object declared in method <R>gather(Gatherer<? super T,?,R>)
T extends Object declared in interface Stream
... (13 more errors trimmed)
$ javac --release 24 Q18_Gatherers.java
(compiles)What you see: windowFixed(3) produced two full chunks and a last chunk of one. The sliding window slid by one each time. scan kept a running total and fold collapsed to one number. mapConcurrent(4) had at most 4 lookups in flight and finished eight 100 ms calls in 231 ms: two rounds, plus start-up. The custom gatherer turned five statuses into [PLACED, COOKING, PLACED]. Release 23 rejects Gatherers as a preview API; release 24 compiles.
Why: Collectors cannot do this because they only run at the end, once. A gatherer is called for each element and decides what flows downstream.
Loop
Hand-made moving window.
List<Double> avg = new ArrayList<>();
for (int i = 0; i + 3 <= v.size(); i++) {
double s = 0;
for (int j = i; j < i + 3; j++)
s += v.get(j);
avg.add(s / 3);
}Gatherer
A window as a stream stage.
List<Double> avg = v.stream()
.gather(Gatherers.windowSliding(3))
.map(w -> w.stream()
.mapToInt(i -> i).average().orElse(0))
.toList();The shift: The window logic moves into the library, and the pipeline reads as what you want.
Land it Gatherers are custom intermediate stream operations with state, so windows, running totals and bounded concurrency become one line in the pipeline.
- "How do I write my own gatherer?"
-
A gatherer has up to four parts, each a small function: an initializer that creates fresh state, an integrator that handles one element (it receives the state, the element and a "downstream" you push results into), an optional combiner for parallel use, and an optional finisher that runs at the end, for example to emit a last partial window.
The integrator returns
trueto keep going orfalseto tell the stream to stop. That is how a gatherer short-circuits, for example "take until the total passes 1000". The demo's deduplicator holds the last element in a one-slot array, skips equal ones and pushes the rest.Use
Gatherer.ofSequential(...)when the logic cannot run in parallel andGatherer.of(...)when you supply a combiner. Most custom gatherers are sequential.Keep them small and test them with plain lists. If you need ten lines of integrator, ask whether a plain loop would be clearer.
- "How is mapConcurrent different from a parallel stream?"
-
A parallel stream splits CPU work across the common fork-join pool and uses about one thread per core.
mapConcurrent(n, fn)is meant for waiting: it runs up toncalls at the same time, each on a virtual thread, so blocking infncosts almost nothing.It also keeps the output order the same as the input order, which a parallel
forEachdoes not. And it limits concurrency with a number you choose, so you can ask a rate-limited service for 4 answers at a time without any pool setup.On failure, it stops launching new work, cancels what is running and rethrows. That is the same idea as structured concurrency, in one stage.
For slow calls like 100 REST requests,
mapConcurrent(10, this::fetch)replaces the executor, the futures list and the join loop. Question 57 shows why a parallel stream is the wrong tool for the same job. - "Can a gatherer run in parallel?"
-
Only a gatherer that supplies a combiner (a function that merges the state of two halves) can run its stage in parallel. Gatherers that depend on element order, such as windows and
scan, run that stage sequentially even inside a parallel stream. Check the Javadoc of each built-in before relying on parallel speed-up.A window across a split boundary is the reason. A sliding window of 3 needs elements from both neighbours, so cutting the input in half would break windows at the cut. The library handles it by running such stages in order.
So do not assume that adding
.parallel()to a pipeline with gatherers speeds up the gatherer stage. Measure.My advice is the same as for all parallel streams: sequential first, parallel only when a measurement shows it helps.
- "What did people use before gatherers?"
-
For windows and batches, a loop, or a library: Guava's
Lists.partition(list, 3)splits a list into chunks, and Apache Commons has similar helpers. For running totals, people usedCollectors.collectingAndThenwith a loop, or anAtomicIntegerinsidemap, which is exactly the side-effect pattern that breaks in parallel.For bounded concurrent calls, an
ExecutorServiceplus a list of futures, or aSemaphore. For distinct-consecutive, a loop or a helper method.The earlier tricks all had one flaw: they sat outside the stream, so you lost the single readable pipeline, or they hid state in a lambda, which is unsafe.
Gatherers keep the state inside the operation, where the library controls it. That is the real gain, more than the saved lines.
These six questions are about the practical side of moving a code base across Java versions: what preview means, how to argue for an upgrade, what breaks, and how a library supports several versions at once.
Q19. "What is a preview feature, and how do you try one safely?"
Reveal answer
Strong answer A preview feature is a complete, working part of the language or the library that the JDK team has released for feedback but has not promised to keep as it is. It may change in the next release or even be removed. Text blocks, records, switch expressions, virtual threads and gatherers all spent one to three releases as previews before becoming final.
To use one you must opt in twice, so nobody uses it by accident. At compile time: javac --release 25 --enable-preview .... At run time: java --enable-preview .... The single-file launcher combines both: java --enable-preview --source 25 File.java.
The compiler marks a class file that uses preview features with a special version: the minor version is 65535. The JVM refuses to run such a class unless --enable-preview is given, and refuses to run it on a different JDK release from the one that compiled it. That is the safety catch: a preview class file is tied to exactly one JDK version.
So the safe ways to try a preview are: in a scratch project, in a test, or in a tool you control end to end. Never in a library you publish and never in code that must run on a JDK you do not control, because next quarter's JDK will refuse to load it.
Some APIs are called incubator modules instead (for example the Vector API). They live in a separate module that you add with --add-modules and are meant for the same purpose.
Picture it The structured concurrency API is still a preview in Java 25, so the same file shows each stage: refused, compiled, refused at run time, and finally running.
The setup: Q19_Preview.java forks two tasks in a StructuredTaskScope, waits for both and prints the results.
import java.util.concurrent.StructuredTaskScope;
public class Q19_Preview {
public static void main(String[] args) throws Exception {
try (var scope = StructuredTaskScope.open()) {
var menu = scope.fork(() -> { Thread.sleep(100); return "menu"; });
var eta = scope.fork(() -> { Thread.sleep(150); return "eta 25 min"; });
scope.join();
System.out.println(menu.get() + " + " + eta.get());
}
}
}Make the invisible visible: Compile and run it with and without the flag, and inspect the class file.
$ javac --release 25 Q19_Preview.java
Q19_Preview.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope;
^
(use --enable-preview to enable preview APIs)
$ javac --release 25 --enable-preview Q19_Preview.java
Note: Q19_Preview.java uses preview features of Java SE 25.
Note: Recompile with -Xlint:preview for details.
$ java -cp out Q19_Preview # run it WITHOUT the flag
Error: LinkageError occurred while loading main class Q19_Preview
java.lang.UnsupportedClassVersionError: Preview features are not enabled for Q19_Preview (class file version 69.65535). Try running with '--enable-preview'
$ java --enable-preview -cp out Q19_Preview
menu + eta 25 min
$ javap -v out/Q19_Preview.class | grep version
minor version: 65535
major version: 69
$ java --enable-preview --source 25 Q19_Preview.java # single-file shortcut
menu + eta 25 minWhat you see: Without --enable-preview the compiler says "StructuredTaskScope is a preview API and is disabled by default". With the flag it compiles, and gives a note about preview use. The class file carries minor version: 65535. Running it without the flag fails with this:
UnsupportedClassVersionError: Preview features are not enabledWith the flag it prints menu + eta 25 min.
Why: The class file version is the safety catch. A preview class is deliberately unloadable by default, and it only loads on the JDK release that produced it.
Without the flag
Compiler refuses.
javac --release 25 Q19_Preview.java
error: StructuredTaskScope is a preview
API and is disabled by default.
(use --enable-preview to enable preview APIs)With the flag
Compiles, and runs only with it.
javac --release 25 --enable-preview ...
java --enable-preview -cp out Q19_Preview
menu + eta 25 min
// same JDK 25 onlyThe shift: Two explicit flags and a locked class-file version keep preview code from reaching production by accident.
Land it A preview is a finished-looking feature released for feedback that needs --enable-preview twice and only runs on the JDK that compiled it.
- "Why do some features stay in preview for years?"
-
Because the feedback changes the design. Structured concurrency has been in preview or incubation since Java 19 and is still preview in 25, 26 and 27. Each round the team changed the API based on how people used it. For example, Java 25 replaced the public constructor with
StructuredTaskScope.open()and a policy object, so the earlier code stopped compiling.The team's rule is that a final feature must be one they will keep for decades, so they prefer another preview to a wrong final. Previews that are stable get finalised without change, like text blocks. Previews that people struggle with get reworked.
It also depends on prerequisites. Some features need a bigger project to land first (for example, value classes planned under Project Valhalla), and the dependent features wait.
As a user, treat a long preview as "useful but the API will move", and do not build a product on it.
- "Can I use a preview in production?"
-
Technically yes, if you control the JDK version and rebuild on every upgrade. Practically almost never. The class file only loads on the exact JDK that compiled it, so a patch of the runtime image, a container base image update or a different JDK vendor with a newer feature release breaks start-up.
The other cost is code churn. When the API changes in the next preview, you rewrite the code. For a feature like virtual threads, which was a preview in 19 and 20, early adopters had to retest and change flags twice before 21 made it final.
The reasonable use is in internal tools, load tests and experiments, to give the JDK team feedback and to learn the feature before it is final. Production gets the final version, usually in the next LTS.
My rule: preview is for learning and for tools that rebuild every release. Anything that ships on a schedule waits for final.
- "How do I switch preview on in Maven or Gradle?"
-
In Maven, pass
--enable-previewto the compiler plugin through<compilerArgs>, set<release>25</release>, and also pass the flag to the plugin that runs the code: Surefire for tests and the exec or Spring Boot plugin for the application, through theirargLineor JVM arguments.In Gradle, add
options.compilerArgs.add("--enable-preview")to theJavaCompiletasks, andjvmArgs("--enable-preview")to theTestandJavaExectasks. Missing the run side is the common mistake: it compiles, then fails at start withUnsupportedClassVersionError.Your IDE needs the same flag in its compiler and run configuration, otherwise it highlights the preview API as an error.
Because the flags are easy to forget in one of four places (compile, test, run, IDE), keep preview code in a separate module or sub-project so the extra flags have one home.
- "What is the difference between preview, incubator and experimental?"
-
Preview features are in the language or core library, finished enough to use, and need
--enable-preview. Incubator modules hold APIs that live outside the mainjava.basemodule underjdk.incubator.*, and you add them with--add-modules jdk.incubator.vector. The Vector API has been an incubator for more than ten releases. Experimental usually describes a JVM feature such as a garbage collector or a runtime option that is switched on with-XX:+UnlockExperimentalVMOptions.All three mean "not final, may change". They differ in where the code lives and which flag opens it.
The JDK release notes say which one applies. In the version cards of this chapter, preview and incubating items are marked so you can see which are safe to rely on.
A safe habit: when a feature sounds attractive, look it up in the release notes and read the word next to it (final, preview, incubator, experimental) before reading the rest.
Q20 · Scenario. "Your team is on Java 17. Make the case for moving to 21 or 25, with concrete wins and risks."
Reveal answer
Strong answer I would start with the target. Move to 25 if you can, because 21 and 25 are both LTS and 25 is the newer one with longer support. Choose 21 only if a dependency (a framework or an agent) does not yet support 25. A two-step plan (17 to 21, then 21 to 25) is a valid fallback, because the jump from 21 to 25 is small.
Concrete wins. From 21: virtual threads (blocking code scales to tens of thousands of concurrent requests with a simple thread-per-request style), pattern matching for switch and record patterns (less casting, exhaustive switches over sealed types) and sequenced collections. From 22 to 25: unnamed variables _, stream gatherers, scoped values, flexible constructors, module imports, no pinning for synchronized in virtual threads (24), faster start-up with AOT class loading (24), and compact object headers (25, a product feature that you switch on and that reduces heap use).
Risks. The Security Manager is permanently disabled (24): System.setSecurityManager now throws. Thread.stop throws UnsupportedOperationException. Libraries that reach into JDK internals via reflection or sun.misc.Unsafe may need updates, and agents (APM, bytecode tools) must support the new class-file version. Build tools and frameworks must support the target. Finally, behaviour changes such as the default charset becoming UTF-8 (18) can alter how files are read.
Plan. Upgrade the build JDK, run the full test suite on 25 with the production flags, read the warnings, test under load, then upgrade the runtime in staging, then production one service at a time.
Picture it A short program uses three Java 21 features. It does not compile on 17 and runs on 21; a second program shows two removals that bite on 25.
The setup: Q20_Wins.java runs 10,000 tasks that each sleep 200 ms on virtual threads, matches a record pattern in a switch, and reverses a list with reversed(). Q20_Risks.java tries to install a Security Manager and call Thread.stop; it is compiled once for release 17 and run on JDK 17 and JDK 25.
import java.util.*;
import java.util.concurrent.*;
public class Q20_Wins {
sealed interface Pay permits Upi, Card {}
record Upi(String handle) implements Pay {}
record Card(String last4) implements Pay {}
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) { // 21: virtual threads
for (int i = 0; i < 10_000; i++) pool.submit(() -> { Thread.sleep(200); return 1; });
} // close() waits for all
System.out.println("10,000 sleeping tasks: " + (System.nanoTime() - t0) / 1_000_000 + " ms");
Pay p = new Card("4242");
System.out.println(switch (p) { // 21: pattern switch
case Upi(var h) -> "upi " + h;
case Card(var l4) -> "card ending " + l4;
});
System.out.println(new ArrayList<>(List.of(1, 2, 3)).reversed()); // 21: sequenced
}
}Make the invisible visible: Compile proofs, the run, and the risk program on both JDKs.
$ javac --release 17 Q20_Wins.java
Q20_Wins.java:17: error: patterns in switch statements are not supported in -source 17
case Upi(var h) -> "upi " + h;
^
(use -source 21 or higher to enable patterns in switch statements)
Q20_Wins.java:17: error: deconstruction patterns are not supported in -source 17
case Upi(var h) -> "upi " + h;
^
(use -source 21 or higher to enable deconstruction patterns)
$ javac --release 21 Q20_Wins.java
(compiles)
10,000 sleeping tasks: 265 ms
card ending 4242
[3, 2, 1]
$ JDK 17: java -cp out Q20_Risks
getSecurityManager(): null
WARNING: A terminally deprecated method in java.lang.System has been called
WARNING: System::setSecurityManager has been called by Q20_Risks (file:/tmp/e21c/q20/)
WARNING: Please consider reporting this to the maintainers of Q20_Risks
WARNING: System::setSecurityManager will be removed in a future release
Thread.stop -> java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "stopThread")
$ JDK 25: java -cp out Q20_Risks
getSecurityManager(): null
setSecurityManager -> java.lang.UnsupportedOperationException: Setting a Security Manager is not supported
Thread.stop -> java.lang.UnsupportedOperationExceptionWhat you see: Release 17 rejects the record pattern, release 21 compiles. The run finished 10,000 tasks that each sleep 200 ms in 272 ms, because virtual threads do not hold an operating-system thread while sleeping. The risk program shows the difference: on 17, setSecurityManager works and prints a deprecation warning; on 25 it throws UnsupportedOperationException. Thread.stop on 25 throws UnsupportedOperationException; on 17 it was denied only because the manager had just been installed.
Why: The wins are new capability, and the risks are removals. Removals fail loudly at start-up or in tests, which is the best way for a risk to appear.
Stay on 17
Known, stable, and falling behind.
+ no work this quarter
+ all libraries support it
- thread per request limits scale
- no virtual threads, no patterns in
switch, no sequenced collections
- support window shrinksMove to 25
Work now, benefits for years.
+ virtual threads, patterns, gatherers
+ faster start-up, smaller headers
+ LTS support for many years
- security manager gone
- some agents and libraries must update
- a testing and rollout projectThe shift: The cost is one planned project; staying costs a little more every quarter because libraries keep raising their minimum Java.
Land it I would propose Java 25, show the virtual thread and pattern-matching wins, name the Security Manager and reflection risks, and upgrade behind a full test run.
- "How do I sell the benefit to a manager who sees no feature value?"
-
I translate features into money and risk. Virtual threads mean a service that waits on the network needs fewer pods for the same traffic, or handles a spike without rejecting requests, so it is a cost and reliability argument. Compact object headers and the newer garbage collectors reduce memory per pod, again a cost argument.
Support is the other lever. Every year on an old LTS means vendors stop patching sooner, security reviews flag it, and libraries drop support. Moving later does not make it cheaper. It makes the jump larger and the pressure tighter.
I also point out hiring and productivity: records, text blocks and pattern switches shorten code, and new developers expect them.
The strongest argument is a measurement. I take one service, run it on 25 in staging with real traffic replay, and show memory, start-up and latency before and after. A graph beats a feature list.
- "What are the practical steps and order of an upgrade?"
-
First, update the build tooling: Maven or Gradle and their plugins must support the new JDK, and Spring Boot or other frameworks must be a version that lists it as supported. Second, compile with the new JDK but keep
--release 17, so you test the toolchain without changing the language level.Third, run the full tests on the new JDK as the runtime, with the real production flags, and read every warning. Fourth, raise
--releaseto 25. Fifth, deploy to staging, run a load test and compare memory and latency. Sixth, roll out to production gradually, one service at a time, with the old image ready to roll back.Throughout, search the code for known problem areas:
setAccessibleon JDK classes,sun.misc.Unsafe,SecurityManager,finalize(),Thread.stop, and flags that no longer exist (the JVM refuses unknown options and will not start).That last check is cheap and finds a lot: grep the start scripts for
-XX:and--illegal-access. - "What breaks most often in real upgrades from 17?"
-
In my experience: old versions of agents and bytecode libraries (APM agents, Mockito versions, ASM, ByteBuddy, Lombok) that do not understand the newer class-file version. They fail with an error such as "Unsupported class file major version 69". The cure is updating those tools, usually a minor version bump.
Next: JVM flags that were removed or deprecated. Garbage collection flags for removed collectors, and logging options, can stop the JVM from starting at all. Test the actual startup script, not just the unit tests.
Then: libraries that rely on reflection into JDK internals; since 17 this is blocked by default and you get
InaccessibleObjectException(question 22).Finally: behaviour drift such as the default charset (UTF-8 in 18), the removed Security Manager (24), and stricter checks on
finalfields (the warnings that Java 26 introduces through JEP 500). - "Should we stop at 21 instead and wait for 25 to settle?"
-
That is reasonable if a key dependency lacks 25 support today. 21 is a strong LTS: it has virtual threads, pattern matching and sequenced collections, and it will be supported for years. The jump 21 to 25 later is small, because 22 to 25 added no breaking removals except the Security Manager's permanent disabling (24).
But 25 is already released and, as an LTS, it will get fixes. Stopping at 21 means you will do a second upgrade project in two years, and you give up the 22 to 25 improvements: no pinning on
synchronizedin virtual threads (a real production issue on 21), unnamed variables, gatherers and scoped values.The pinning point matters if you plan to use virtual threads heavily. On 21,
synchronizedblocks that wait on I/O can pin the carrier thread, so some libraries need workarounds. That is gone in 24 and later.So: 25 if the dependencies allow, 21 as a stepping stone otherwise.
Q21 · Scenario. "After an upgrade, code fails to compile with “'var' is a restricted type name”. What happened?"
Reveal answer
Strong answer Somewhere in the code base there is a type called var: a class, interface, enum or type parameter named var. That was legal in Java 8 and 9. From Java 10, var is a reserved type name, so declaring a type with that name is an error. The upgrade moved the compiler past 9 and the old name stopped compiling.
The exact wording differs slightly by compiler version. On JDK 25 it reads 'var' not allowed here followed by this:
as of release 10, 'var' is a restricted type name and cannot be used for type declarationsThe words "restricted type name" are the stable part.
The fix is to rename the type. The conventional name is Var or something that says what it is. Rename it with the IDE's refactoring so all references change together, including strings in reflection, config files and serialised data that mention the class name.
What still works: a variable, parameter, field or method named var is legal (int var = 5;). That is why most programs are not affected, and why this error is rare. If the type came from a library, upgrade the library, because it must have been fixed long ago.
It is a good first example of the general rule for upgrade failures: read the first error, find the removed or restricted thing, rename or replace it, and rebuild.
Picture it A class named var compiles under release 9 and fails under release 10, and the renamed class compiles everywhere.
The setup: Q21_Legacy.java declares static class var, creates it with var v = new var(); and also has an int var variable. Q21_Fixed.java renames the class to Var.
public class Q21_Legacy {
static class var { // legal in Java 8 and 9
String text = "I am a class called var";
}
public static void main(String[] args) {
var v = new var();
System.out.println(v.text);
int var = 5; // a variable named var is still fine
System.out.println(var + 1);
}
}Make the invisible visible: Compile the legacy file with 9 and 10, then compile and run the fixed one.
$ javac --release 9 Q21_Legacy.java
(compiles)
$ javac --release 10 Q21_Legacy.java
Q21_Legacy.java:2: error: 'var' not allowed here
static class var { // legal in Java 8 and 9
^
as of release 10, 'var' is a restricted type name and cannot be used for type declarations
$ javac --release 10 Q21_Fixed.java
(compiles)
I am a class called Var
6What you see: Release 9 compiles. Release 10 stops at the class declaration with the restricted-type-name message. The renamed file compiles on release 10, runs, and prints 6 from int var = 5; var + 1, which proves a variable named var is still fine.
Why: From 10, the word var in a type position means "infer it". A class with that name would make var v = new var() ambiguous, so the language forbids the class and keeps the variable name legal.
Java 9
A class named var is allowed.
class var {
String text = "hello";
}
var v = new var();
int var = 5;Java 10+
Rename the type.
class Var {
String text = "hello";
}
var v = new Var(); // inferred: Var
int var = 5; // still legalThe shift: Only the type name is restricted; variables, methods and packages called var keep working.
Land it The error means a type named var exists; I rename it to Var and rebuild, since variables named var are still legal.
- "How do I find every occurrence quickly?"
-
Compile once with the new JDK and read the error list. The compiler reports each declaration, so you get a complete list in one run. Starting from the file names and line numbers, fix them with an IDE rename, which updates the references.
A text search helps for things the compiler does not see:
grep -rn "class var\b"andinterface var\b, plus strings in XML, YAML or JSON config where the class name might appear (Spring bean definitions, serialisation type ids).If the type is part of a serialised format, such as Java serialisation or a JSON field that holds a class name, the rename is a data change as well. Keep a mapping layer or migrate the stored data.
If the culprit is inside a third-party jar, check whether a newer version exists. The author must have renamed it, since that jar could never compile on Java 10 or later.
- "Are there other names that became restricted in later Java versions?"
-
Yes, a family of contextual keywords was added the same way:
yield(14),record(16),sealedandpermits(17). They are special only in a certain position of the grammar, so a variable or method namedrecordoryieldstill compiles.The restrictions are on type names. A class called
recordoryieldis rejected from the release that introduced the word. A method namedyieldmust be called with a qualifier (this.yield()orThread.yield()), because an unqualified call is read as the new statement. That one broke some thread code.The single underscore is another case. It was a legal identifier up to Java 8, an error from 9, and since Java 22 it means an unnamed variable (question 9).
So the pattern of upgrade failures is the same each time: a name the old code used for itself has been taken by the language.
- "Why did Java break old code instead of grandfathering it?"
-
Because a name used both ways would force the parser to guess. In
var v = ..., doesvarmean the class or the new type inference? Allowing both makes the grammar ambiguous and the rules complicated for everybody.The language team judges each such break by how much code it affects. A class named
varis extremely rare, since lowercase class names go against every style guide, so the break was cheap. Makingvara full keyword would have broken variables namedvar, which is far more common, so they chose the narrower rule.The compiler supports
-source 9(or--release 9) for exactly this situation. You can keep an old module at the old language level while you rename the type, as the demo's first compile shows.That is the model for upgrades in general: separate "upgrade the JDK" from "raise the language level" and do them one at a time.
- "How can I keep an old module compiling while I migrate?"
-
Compile it with an older language level:
javac --release 9or, in Maven,<release>9</release>for that module. The new JDK compiles the old code, and you can run it on the new JVM. That lets you upgrade the runtime first and the language level second.--releaseis better than-sourceand-target, because it also restricts the library API to what existed in that release, so you do not accidentally call a method that the older JVM lacks. Question 24 shows that difference with a compile proof.In a multi-module build, set
releaseper module, and raise each as it becomes ready. A shared parent can define the default.The temporary state should have an owner and an end date. A module stuck on
--release 8for years is a risk of its own, since you lose every feature in this chapter in that module.
Q22 · Scenario. "After moving from Java 8 to 17, the app fails at start-up with InaccessibleObjectException. Explain and fix."
Reveal answer
Strong answer A library (or your own code) is using reflection to open a private part of the JDK, with setAccessible(true) on a field or method of a class like java.lang.String or java.util.ArrayList. On Java 8 that worked. From Java 16, and strictly in 17, the JDK's internal packages are strongly encapsulated: they are not open to deep reflection from code outside the JDK, and the call throws java.lang.reflect.InaccessibleObjectException.
The message names the exact package:
module java.base does not "opens java.lang" to unnamed moduleThat sentence is the whole diagnosis: module java.base, package java.lang, and the caller (your classpath code lives in the "unnamed module").
Short-term fix: add a JVM flag that opens that package to your code: --add-opens java.base/java.lang=ALL-UNNAMED. Add one flag per package named in the errors.
Real fix: upgrade the library that reaches in (most popular ones fixed it years ago: Spring, Hibernate, Jackson, Mockito, Lombok, Gson), or replace the use of internals with a public API. If it is your own code, stop poking at JDK private fields, and use the public method.
In Java 9 to 15 the default was "permit, with a warning" through --illegal-access=permit. Java 16 changed the default to deny, and Java 17 removed the flag. That is why this error arrives exactly when a team jumps from 8 to 17.
Picture it A program reads the private value field of String. It works on JDK 8, fails on JDK 17 and 25 with the exact message, and works on 17 again with --add-opens.
The setup: Q22_Reflect.java asks for the private field value of String, calls setAccessible(true) and reads its length. It is compiled once and run on three JDKs.
import java.lang.reflect.Field;
public class Q22_Reflect {
public static void main(String[] args) throws Exception {
Field f = String.class.getDeclaredField("value"); // a private field inside the JDK
f.setAccessible(true); // 8: fine. 16+: throws unless the package is opened
System.out.println("read String.value, length " + java.lang.reflect.Array.getLength(f.get("hi")));
}
}Make the invisible visible: Run it on JDK 8, then 17, then 17 with the flag, then 25.
$ JDK 8: java Q22_Reflect
read String.value, length 2
$ JDK 17: java Q22_Reflect
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module @70ffb6f
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
$ JDK 17: java --add-opens java.base/java.lang=ALL-UNNAMED Q22_Reflect
read String.value, length 2
$ JDK 25: java Q22_Reflect
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module @2b2fa4f7
at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:353)What you see: JDK 8 printed the length, so it never complained. JDK 17 threw this:
InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible:
module java.base does not "opens java.lang" to unnamed moduleWith --add-opens java.base/java.lang=ALL-UNNAMED, 17 worked again. JDK 25 fails the same way as 17. The field type tells another story: byte[] on 17, because Java 9 changed strings to a compact byte array. Code that depended on the old char[] was fragile anyway.
Why: Strong encapsulation is a promise that the JDK can change its private code without breaking you. The flag is an escape hatch, not a fix.
Java 8
Reflection into the JDK works.
Field f = String.class
.getDeclaredField("value");
f.setAccessible(true); // fine
char[] chars = (char[]) f.get("hi");Java 17
Same call throws.
java.lang.reflect.InaccessibleObjectException:
Unable to make field private final byte[]
java.lang.String.value accessible:
module java.base does not "opens java.lang"
to unnamed moduleThe shift: The JDK now keeps its private parts private, and the error message names exactly which door is closed.
Land it The library reflects into a JDK internal that Java 16 and 17 closed; I add the --add-opens flag from the message as a stopgap and upgrade or replace the library for the real fix.
- "What exactly does --add-opens do, and when is it acceptable?"
-
--add-opens module/package=targettells the JVM to open one package of one module for deep reflection to a target, which isALL-UNNAMEDfor ordinary classpath code. It affects only that package, so the flag in the demo opensjava.langand nothing else. It does not change the code, and it is cheap at run time.It is acceptable as a bridge: when you must run a library that has not been updated, when a vendor tool needs it, or in tests. Every flag should have a comment and a ticket to remove it.
Where to put it: in the
javacommand line, inJAVA_TOOL_OPTIONS, or in theJARmanifest throughAdd-Opensfor executable jars. Maven Surefire needs it inargLineso tests see it too.A sign that things are going wrong: a long list of
--add-openslines. That means several libraries are outdated, and the right move is updating them. - "What is the difference between --add-opens and --add-exports?"
-
--add-exportsmakes the public types of a package visible to the compiler and at run time, so code outside the module can use them normally. It does not allow reflection on private members. You need it when you call an internal API directly, such assun.miscclasses in some packages orcom.sun.tools.--add-opensincludes everything that export does, and in addition allowssetAccessible(true)on private members. Frameworks that use reflection (serialisers, dependency injection, test mocking tools) needopens.The rule: if the failure is
IllegalAccessErroron a call, use exports. If it isInaccessibleObjectExceptiononsetAccessible, use opens.Both are escape hatches. Prefer to remove the need: public APIs exist for most things people used to do with internals, for example
MethodHandles.privateLookupInfor your own classes. - "Why did Java 9 to 15 only warn and 16 and 17 start failing?"
-
The JDK team introduced modules in Java 9 and wanted to lock down the internals, but a hard break would have stopped most applications at once. So Java 9 to 15 had
--illegal-access=permitas the default: reflection into JDK internals still worked, with one warning on the first use ("An illegal reflective access operation has occurred"). That period was meant to give libraries time to update.Java 16 (JEP 396) switched the default to
deny, but you could still set--illegal-access=permitto go back. Java 17 (JEP 403) removed the option, so only--add-opensworks.Apps that ran fine for years on 11 with a warning in the log therefore fail on 17. Search old logs for "illegal reflective access" before you upgrade: every such warning is a future failure.
The warning text names the library and the package, which gives you the list of libraries to upgrade in advance.
- "Which libraries or tools usually cause it?"
-
Older versions of serialisation and mapping libraries (Gson, XStream, Kryo), dependency-injection and AOP frameworks, test mocking tools (Mockito and PowerMock on old versions), ORMs such as old Hibernate, and bytecode tools. Application servers and build plugins sometimes need flags too.
The usual cure is a version bump. Spring Framework 5.3+ and Spring Boot 2.5+ run on 17. Hibernate 5.6 and 6, Jackson 2.13+, Mockito 4 and 5 and recent Lombok versions are fine on 17 and later.
The one that has no easy cure is your own code that uses
sun.misc.Unsafeor private JDK fields. Replace it with the public API, for exampleVarHandleinstead ofUnsafefor atomics, orMethodHandles.Lookupfor private access to your own classes.My checklist before upgrading: read dependency release notes for "Java 17 support", run the tests on 17, and grep startup logs for "illegal reflective access".
Q23. "What changed in Java 26 and 27, and why did they add no new final language syntax?"
Reveal answer
Strong answer Honest scope: this is from the release notes, because the course machine runs JDK 25 and the compiler cannot target 26 or 27 (shown below). Java 26 shipped on 17 March 2026 and Java 27 on 15 September 2026. Neither is an LTS.
Java 26: JEP 500 "prepare to make final mean final" starts warning when deep reflection changes a final field. JEP 517 adds HTTP/3 to the HTTP client. JEP 516 allows AOT object caching with any garbage collector, JEP 522 improves G1 throughput and JEP 504 removes the old Applet API. Previews continued: structured concurrency (6th), lazy constants (2nd, formerly stable values), primitive types in patterns (4th) and PEM encodings.
Java 27: JEP 523 makes G1 the default collector in all environments, JEP 534 turns compact object headers on by default, JEP 527 adds post-quantum hybrid key exchange to TLS 1.3 and JEP 536 adds in-process data redaction to Flight Recorder. Previews continued again (structured concurrency 7th, lazy constants 3rd, primitive types in patterns 5th).
Why no new final syntax: language changes need several previews to settle, and the pipeline from 22 to 25 finished a large batch (unnamed variables, flexible constructors, module imports, compact source files). The next big language work, Valhalla's value objects (JEP 401), is planned for a later release (JDK 28 is the stated target, but check the OpenJDK page), so nothing finished was waiting to ship. Quiet language releases are normal. Not every release changes syntax.
Picture it The honest limit of what can be run: JDK 25's compiler does not know releases 26 or 27, and the one reflection behaviour that Java 26 starts warning about still works silently on 25.
The setup: Q23_Final.java uses reflection to change a final instance field. The field is read from a non-constant expression so the compiler does not inline it. A small script then asks javac for releases 25, 26 and 27.
import java.lang.reflect.Field;
public class Q23_Final {
static class Config {
private final int maxRetries = Integer.parseInt("3"); // not a compile-time constant
int maxRetries() { return maxRetries; }
}
public static void main(String[] args) throws Exception {
Config c = new Config();
Field f = Config.class.getDeclaredField("maxRetries");
f.setAccessible(true);
f.setInt(c, 99); // deep reflection mutating a final field
System.out.println("maxRetries() = " + c.maxRetries());
}
}Make the invisible visible: Run the program, then compile for 25, 26 and 27.
maxRetries() = 99
$ javac --release 25 Q23_Final.java
$ javac --release 26 Q23_Final.java
error: release version 26 not supported
Usage: javac <options> <source files>
$ javac --release 27 Q23_Final.java
error: release version 27 not supported
Usage: javac <options> <source files>
openjdk version "25.0.5.1" 2026-11-17What you see: On JDK 25 the final field is changed silently: maxRetries() = 99. javac --release 26 and 27 both answer "release version not supported", so this machine cannot compile or run them. On Java 26, this reflection call is described by the release notes as printing a warning, and a later release is expected to refuse it by default. That behaviour was not run here.
Why: JEP 500 exists so the JVM can trust final fields, which allows more optimisation. The warnings come first, so libraries that change finals (some serialisers and mocking tools) have time to adapt.
Java 25
Final field changed silently.
f.setAccessible(true);
f.setInt(config, 99);
// no warning, value changes
// (as measured above)Java 26 (notes)
A warning on first use.
f.setAccessible(true);
f.setInt(config, 99);
// WARNING printed (per JEP 500)
// later: denied by defaultThe shift: The language's promise that final means final is being enforced step by step, not in one break.
Land it Java 26 and 27 changed the platform, with final-means-final warnings, HTTP/3, G1 as default and compact headers, but not the syntax, because the next language features were still in preview.
- "What is JEP 500 and who is affected?"
-
JEP 500 is "Prepare to make final mean final". Today the JVM lets code change a
finalfield through reflection (setAccessible(true)thenset), throughUnsafeand some other routes. That means the compiler and the JIT cannot assume a final field never changes, so they lose some optimisations. The JEP starts a path: Java 26 warns when it happens, and a later release will throw unless you opt in with a flag.Who is affected: libraries that set final fields to build objects without calling constructors: some serialisation libraries, some mocking and testing tools and some dependency injection frameworks. Normal application code rarely does it.
What to do: run your tests on 26 or later and watch for the warning, then update the library that causes it. If you control the code, stop mutating final fields and use a constructor or a non-final field.
Check the Java 26 release notes for the exact warning text and the flag names, because I have not run it here.
- "Why does the demo field use Integer.parseInt instead of = 3?"
-
Because of a compiler optimisation that surprises people. A
finalfield with a constant initialiser, such asprivate final int maxRetries = 3;, is a constant variable. The compiler copies its value into every place that reads it, so a reader never looks at the field. If reflection changes the field afterwards, the code that readsmaxRetriesstill sees3. In my first test of this demo that is exactly what printed.When the initialiser is not a compile-time constant (here
Integer.parseInt("3")), the reads go through the field and see99.That is a nice illustration of why changing finals is dangerous: the same program can show the old or new value depending on how the initialiser is written. The JEP wants to end that uncertainty.
It is also why you should never rely on reflection to configure a final field in your own code.
- "What happened to the preview features, and will they ever finish?"
-
Structured concurrency (preview in 19 to 27 counting its incubator), lazy constants (previously called stable values) and primitive types in patterns continue as previews. In each release the team adjusts the API from feedback. Lazy constants are the only one of these that offers a way to initialise a value at most once and then treat it as constant.
They will finish when the design stops changing. I would not predict which release. The JDK team also lists these in JEPs with status, so check the OpenJDK site for the current state when you read this.
For planning, do not count on either becoming final in a particular release. Until they do, keep them out of production code that ships.
The same rule applies as for every preview: learn it, try it in tools and tests, wait for final for production.
- "What is the point of upgrading to a non-LTS like 26 or 27?"
-
For application teams, usually none. Support ends six months after release, so you would upgrade again soon. The reasons to try one are to test your dependencies early (so the next LTS upgrade holds no surprise), to try a preview, or to benefit from a specific improvement such as a garbage collector change that you have measured.
Library authors have a stronger reason: their users will move to 25 and later, and finding a break in 26 or 27 early is cheaper than learning about it from an issue report.
A good habit is a CI job that builds and tests your code on the latest non-LTS release and reports failures without blocking the main build. That gives you early warning at little cost.
For production, LTS only: 25 now, and 29 when it arrives in September 2027.
Q24 · Design. "You maintain a library used by apps on Java 8, 17 and 25. How do you build, test and release it?"
Reveal answer
Strong answer Principle: the library must run on the oldest Java its users have, and may use newer features only where they are available. Everything else follows from that.
Build. Compile the main code with javac --release 8, not -source 8 -target 8. --release also restricts the library API to what Java 8 has, so a call like List.of fails to compile instead of failing in a customer's JVM.
If you want newer features for some classes, put those in a multi-release JAR: the base classes are compiled for 8, and a second copy of selected classes compiled with --release 17 (or 21) goes under META-INF/versions/17/. Newer JVMs load the newer copy, older ones ignore it.
Test. Run the same test suite on every JDK you promise to support: 8, 17, 21 and 25 in a CI matrix. Compile with one JDK (the newest, using --release 8) and run the tests on each, using Maven toolchains or Gradle's Java toolchain support. Add a check that the code uses only Java 8 API (animal-sniffer or the --release flag itself). Also build against the newest non-LTS release in a non-blocking job to see breakage coming.
Release. Publish one artifact with the right Multi-Release: true manifest entry. Set Automatic-Module-Name so modular apps can use it. State the supported range in the README, follow semantic versioning, and announce the date you will drop Java 8, giving users a major version to move to. Avoid preview features and JDK internals, since neither survives across versions.
Picture it A two-version library is built with the right flags, packed into a multi-release JAR, and run on JDK 8, 17, 21 and 25. First the trap that --release avoids.
The setup: Q24_Api.java calls List.of (Java 9). It is compiled once with the old -source 8 -target 8 pair and then with --release 8 and 9.
import java.util.List;
public class Q24_Api {
public static void main(String[] args) {
System.out.println(List.of("a", "b")); // Java 9 API
}
}--- same file, wrong way: -source/-target only checks syntax, not the API
$ javac -source 8 -target 8 Q24_Api.java
warning: [options] bootstrap class path is not set in conjunction with -source 8
not setting the bootstrap class path may lead to class files that cannot run on JDK 8
--release 8 is recommended instead of -source 8 -target 8 because it sets the bootstrap class path automatically
(compiles: it still links against the JDK 25 class library)
--- right way
$ javac --release 8 Q24_Api.java
Q24_Api.java:5: error: cannot find symbol
System.out.println(List.of("a", "b")); // Java 9 API
^
symbol: method of(String,String)
location: interface List
$ javac --release 9 Q24_Api.java
(compiles)What you see: The -source 8 -target 8 compile succeeded: it only restricts the language syntax and still links against JDK 25's class library, so the Java 9 call slipped through (with a warning that recommends --release). --release 8 fails with "cannot find symbol: method of(...)", and --release 9 compiles.
The setup: Now the library itself: class com.qb.Ids exists twice, a baseline copy built with --release 8 and a variant built with --release 17. The jar command packs the second copy under META-INF/versions/17.
package com.qb;
public class Ids {
public static String describe() { return "Java 8 baseline: " + java.util.UUID.randomUUID().toString().length() + " chars"; }
public static String runtime() { return System.getProperty("java.specification.version"); }
}package com.qb;
public class Ids {
public static String describe() { return "Java 17 variant: uses RandomGenerator " + java.util.random.RandomGenerator.getDefault().getClass().getSimpleName().length(); }
public static String runtime() { return System.getProperty("java.specification.version"); }
}set -e
rm -rf out && mkdir -p out/base out/v17 out/app
echo '$ javac --release 8 -d out/base base/com/qb/Ids.java'
javac --release 8 -Xlint:-options -d out/base base/com/qb/Ids.java
echo '$ javac --release 17 -d out/v17 v17/com/qb/Ids.java'
javac --release 17 -d out/v17 v17/com/qb/Ids.java
javac --release 8 -Xlint:-options -cp out/base -d out/app App.java
echo '$ jar --create --file qb.jar -C out/base . --release 17 -C out/v17 .'
jar --create --file qb.jar -C out/base . --release 17 -C out/v17 .
echo; jar tf qb.jar | grep -E "Ids|versions"
echo; echo "Multi-Release: $(unzip -p qb.jar META-INF/MANIFEST.MF | grep -i multi)"
for v in 8 17 21; do echo "\$ java-$v -cp qb.jar:out/app App"; /usr/lib/jvm/java-$v-openjdk-amd64/bin/java -cp qb.jar:out/app App; done
echo "\$ java-25 -cp qb.jar:out/app App"; java -cp qb.jar:out/app AppMake the invisible visible: Build the jar and run the same App on four JDKs.
$ javac --release 8 -d out/base base/com/qb/Ids.java
$ javac --release 17 -d out/v17 v17/com/qb/Ids.java
$ jar --create --file qb.jar -C out/base . --release 17 -C out/v17 .
com/qb/Ids.class
META-INF/versions/17/
META-INF/versions/17/com/
META-INF/versions/17/com/qb/
META-INF/versions/17/com/qb/Ids.class
Multi-Release: Multi-Release: true
$ java-8 -cp qb.jar:out/app App
Java 8 baseline: 36 chars [running on 1.8]
$ java-17 -cp qb.jar:out/app App
Java 17 variant: uses RandomGenerator 15 [running on 17]
$ java-21 -cp qb.jar:out/app App
Java 17 variant: uses RandomGenerator 15 [running on 21]
$ java-25 -cp qb.jar:out/app App
Java 17 variant: uses RandomGenerator 15 [running on 25]What you see: The jar lists com/qb/Ids.class plus a copy under META-INF/versions/17/, and the manifest says Multi-Release: true. JDK 8 printed "Java 8 baseline". JDK 17, 21 and 25 all printed "Java 17 variant". The application code and the jar are the same bytes on every run.
Why: The JVM's class loader checks the manifest and picks the highest versioned copy it can handle. The user does nothing and the library author keeps one artifact.
Wrong
Syntax level only.
javac -source 8 -target 8 Lib.java
# compiles List.of, Java 9 API
# crashes later on a Java 8 JVM:
# NoSuchMethodError: List.ofRight
Syntax and API level.
javac --release 8 Lib.java
# error: cannot find symbol: List.of
# you fix it before shippingThe shift: --release makes the compiler see the old library, so a wrong call is a build error instead of a customer's crash.
Land it I compile with --release 8, add newer variants through a multi-release JAR, run the tests on every supported JDK in CI, and announce when Java 8 support ends.
- "Why not compile on Java 8 itself?"
-
You can, and for a while that is what everyone did. The cost is that your build then runs on an old JDK that no longer gets the newest tools, your CI images are old, and you cannot use the newer compiler's improved diagnostics. Many plugins also require a newer JDK to run.
Building with a modern JDK and
--release 8gives you the best of both: a current toolchain and a guarantee of Java 8 compatibility, because the API visible to the compiler is exactly Java 8's. Be aware that JDK 25 prints an "obsolete" warning for--release 8and that a future JDK will remove it. Plan for the day that you must raise the baseline to 11 or 17.Testing still needs a real Java 8 JVM, since compile checks do not catch behaviour differences such as changed default garbage collector or
Stringinternals.My setup: JDK 25 builds,
--release 8, and the test job runs under 8, 17, 21 and 25 images. - "When do I use a multi-release JAR and when not?"
-
Use it when one class has a much better implementation on a newer JVM and you want to ship both. Examples: using
VarHandleinstead ofUnsafe, usingRuntime.version()in place of parsing a system property, or using virtual threads (21) where available while keeping a thread-pool fallback.The rules are strict. Every versioned class must have the same public API as the base class, otherwise users see different behaviour per JVM. The base classes must not depend on versioned ones in ways that break. Test each variant on its own JVM.
Do not use it just for style. Each variant is another thing to test. If a feature is nice but not important (records instead of classes), keep to the baseline.
The other route is splitting into two artifacts:
libandlib-java21, with the user choosing. That is simpler to reason about and is common when the difference is large, for instance when the newer version needs a different dependency. - "How do I test on several JDKs without a mess?"
-
Use your build tool's toolchain support. In Maven, the toolchains plugin lets a build compile with one JDK and run Surefire with another, picked from a file of installed JDKs. In Gradle,
java.toolchainand thejavaLauncherproperty of theTesttask do the same, and can download the JDK.In CI, use a matrix: one job per JDK version (8, 17, 21, 25) that runs the tests with that runtime. GitHub Actions, GitLab and others make it a few lines. Add a job with the latest non-LTS release marked as allowed to fail.
Keep the matrix honest about the dependencies. Java 8 needs older versions of test libraries (JUnit 5 is fine, Mockito 4 is the last line for 8), so a separate test dependency set may be required.
The test I find most valuable is a tiny "smoke" application that depends on the built jar and runs on each JDK, because it catches packaging mistakes that unit tests inside the project do not see.
- "When and how do I drop Java 8?"
-
Look at your users, not at the calendar. Check download statistics, ask in issues and look at which frameworks your users run (Spring Boot 3 and later require 17). When most users are off Java 8 and a feature you want needs a newer baseline, announce a drop with a release or two of notice.
Raise the baseline in a major version, so users who cannot move can stay on the previous major, and keep fixing serious bugs in it for a stated period. Update the CI matrix and the
--releasevalue.Benefits: records,
var, text blocks,HttpClient, and fewer compatibility shims. Cost: users on the old Java lose updates.Say it in a clear sentence in the README: "version 3.x supports Java 8 to 25, version 4.x requires Java 17 or later". People plan around that sentence.
Q25 · Design. "Write the “modern Java” cheat sheet you would hand a Java 8 developer: the ten one-liners that change daily code."
Reveal answer
Strong answer I would pick the ten changes that remove the most daily code, in the order a person is likely to meet them. Each one is a line they can paste.
- var (10):
var orders = new ArrayList<Order>();The type is written once. - Immutable factories (9):
List.of(a, b),Map.of("k", 1),Set.of(...). Use for constants and fixed data. - Records (16):
record Item(String name, int cents) {}replaces a 40-line data class. Switch expressions (14):
a switch expressionruns offlineString kind = switch (n) { case 0 -> "empty"; default -> "many"; };- Text blocks (15):
"""for JSON, SQL and HTML, with.formatted(...)to fill values. - Pattern matching instanceof (16):
if (o instanceof Item i && i.cents() > 0)with no cast. - Stream.toList() (16):
stream.map(...).toList()instead ofcollect(Collectors.toList()). - String helpers (11):
isBlank(),strip(),repeat(n),lines(). - Files and sequenced collections (11, 21):
Files.readString(path)andlist.getLast(). - Virtual threads (21):
Executors.newVirtualThreadPerTaskExecutor()for blocking work with one thread per task.
Beyond the ten, three notes complete the sheet: use --release for the target, prefer sealed types with a pattern switch for closed sets of cases, and treat preview features as experiments.
Picture it All ten, in one small file, run on JDK 25, with compile proofs that the file does not build on Java 8 and does on 21.
The setup: Q25_Ten.java uses each of the ten, marked by a comment number. It writes and reads a temp file and runs one task on a virtual thread.
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
public class Q25_Ten {
record Item(String name, int cents) {} // 3 record (16)
public static void main(String[] args) throws Exception {
var menu = List.of(new Item("biryani", 24900), new Item("raita", 4900)); // 1 var (10) 2 List.of (9)
var prices = Map.of("biryani", 24900, "raita", 4900); // 2 Map.of (9)
String kind = switch (menu.size()) { case 0 -> "empty"; case 1 -> "single"; default -> "many"; }; // 4 (14)
String json = """
{"items": %d, "kind": "%s"}
""".formatted(menu.size(), kind); // 5 text block (15) + formatted
System.out.print(json);
Object o = menu.getFirst(); // 9 getFirst (21)
if (o instanceof Item i && i.cents() > 10000) System.out.println("pricey: " + i.name()); // 6 (16)
var names = menu.stream().map(Item::name).toList(); // 7 Stream.toList (16)
System.out.println(names + " " + prices.get("raita") + " " + " ".isBlank()); // 8 isBlank (11)
Path p = Files.writeString(Files.createTempFile("qb", ".txt"), "gold\n"); // 8 Files.writeString (11)
System.out.print(Files.readString(p));
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) { // 10 virtual threads (21)
System.out.println(exec.submit(() -> Thread.currentThread().isVirtual()).get());
}
}
}Make the invisible visible: Run, then compile with 8 and 21.
{"items": 2, "kind": "many"}
pricey: biryani
[biryani, raita] 4900 true
gold
true
$ javac --release 8 Q25_Ten.java
Q25_Ten.java:6: error: records are not supported in -source 8
record Item(String name, int cents) {} // 3 record (16)
^
(use -source 16 or higher to enable records)
... (4 more errors trimmed)
$ javac --release 21 Q25_Ten.java
(compiles)What you see: The text block printed JSON with the item count, the pattern matched the biryani, Files.writeString and readString round-tripped the word "gold", and the virtual-thread check printed true. On release 8 the first error is the record, with four more trimmed. Release 21 compiles the whole file.
Why: Each line would take between four and forty lines in Java 8 style. That is the whole case for the cheat sheet.
| Daily job | Java 8 habit | One-liner now | Since |
|---|---|---|---|
| Declare a local | Map<String, List<Order>> m = new HashMap<>(); | var m = new HashMap<String, List<Order>>(); | 10 |
| Small constant list | Arrays.asList("a","b") | List.of("a", "b") | 9 |
| Data class | class, getters, equals, hashCode, toString | record Item(String n, int c) {} | 16 |
| Return from a branch | switch statement with break | return switch (s) { case A -> 1; ... }; | 14 |
| Multi-line text | "{\n" + ... | """ block | 15 |
| Test and cast | if (o instanceof T) { T t = (T) o; } | if (o instanceof T t) | 16 |
| End of a pipeline | .collect(Collectors.toList()) | .toList() | 16 |
| Blank check | s.trim().isEmpty() | s.isBlank() | 11 |
| Read a file, last item | reader loop; get(size() - 1) | Files.readString(p); list.getLast() | 11 / 21 |
| Many blocking calls | pool of 200 threads | newVirtualThreadPerTaskExecutor() | 21 |
Java 8
Verbose, but it works.
List<String> n = Arrays.asList("a", "b");
Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
String s = o instanceof String
? (String) o : "";
List<Integer> l = st.collect(
Collectors.toList());Modern
Same intent, less ceremony.
var n = List.of("a", "b");
var m = Map.of("a", 1);
String s = o instanceof String t
? t : "";
var l = st.toList();The shift: The ten changes remove casts, fillers and wrappers, and none of them changes what the program means.
Land it The ten are var, List.of, records, switch expressions, text blocks, instanceof patterns, toList, the String helpers, readString with getLast, and virtual threads.
- "Which of the ten is the highest value?"
-
For most code it is records, because data classes are everywhere and each one saves dozens of lines and a class of bugs (a forgotten field in
equals). The second is the switch expression with sealed types, because it makes the compiler check completeness. The third isStream.toList()and the String helpers, which are small but used daily.Virtual threads have the largest effect on a particular kind of service, one that spends most of its time waiting on the network or a database. For those it changes the capacity story. For a batch job or a computation, they change nothing.
Which one matters most depends on the code base. In an interview I would give this order and then say that I would profile and read the code first before pushing any of them on a team.
The cheapest to adopt is
varandList.of, since they need no design decisions at all. - "What would you leave off the list, and why?"
-
Things that are important but not daily: modules (most applications never write
module-info.java), the Flow API,CompletableFuture(it is Java 8 and should already be known), records patterns and gatherers (powerful but narrower), and preview features of any kind.I would also leave off the JVM-level improvements such as garbage collector defaults and compact headers. They help a lot but need no code change, so they do not belong on a "what do I type" sheet. They belong on an "upgrade benefits" slide.
Security and library removal also belong elsewhere: they are a checklist for migration, not a cheat sheet.
A cheat sheet is only useful if it is short. Ten items fit on a card, twenty do not.
- "How would you teach this to a team in practice?"
-
Not with a slide. I would run a one-hour code-along on a real file from our own project: refactor a 200-line class with the ten items one by one, running the tests after each step. People remember what they changed with their own hands.
Then I would put the card where they work: in the repository wiki, with before and after snippets from our own code. And add checks: IDE inspections and static analysis (SonarQube, Error Prone) can flag the Java 8 patterns automatically, such as an instanceof followed by a cast, or a data class that could be a record.
Finally, I would apply the changes only in code we are already touching, never in a mass rewrite. Large mechanical diffs hide real changes in review.
The card is the start. The inspection rules are what keep the habits alive.
- "How do I know the one-liners really compile on every version I claim?"
-
I would not trust the labels on a card. The proof is to compile them. Each row of the table has a version number, and the way to check is the one used throughout this chapter: compile a small file with
--release N-1and expect a failure, then with--release Nand expect success. A script can do that for every row in a few seconds, and it can be run again when a new JDK arrives.The demo file does this for the ten items together: release 8 fails and release 21 passes, since the virtual-thread line is the newest (21). A stricter check would use one file per row.
Such a script also protects the sheet from going stale. If a row's claim is wrong, for example because a method was added one release later than remembered, the check fails and you fix the card.
That is the habit the whole chapter has tried to teach: when you say "since Java N", you should be able to show the compiler agreeing.
14 · DrillLambdas, Streams and Collectors — Q26–Q60
These thirty-five questions cover the functional half of modern Java: lambdas and the interfaces they fit, how a stream pipeline really executes, the collectors that finish it, and when a parallel stream helps or hurts. Interviewers go beyond "what does map do". They ask what runs when, what is shared between threads and what a pipeline costs.
Every answer uses the chapter's QuickBite data: the twelve orders from the primer, loaded from three small files that sit next to each program. The records are shown once here. Data.java holds the twelve orders as Data.ORDERS, exactly as in the primer sections. Programs are in code/e21-modern-java/E/ and run with plain java QNN_Name.java on JDK 25 (the launcher finds the three data files automatically).
record Line(String item, int qty, int priceCents) {}import java.util.List;
record Order(int id, String restaurant, String customer, String city, String day,
String status, List<Line> lines) {
int totalCents() {
return lines.stream().mapToInt(l -> l.qty() * l.priceCents()).sum();
}
}Timings were measured on the course machine (12 cores, other jobs running at the same time), so read the ratios and not the exact milliseconds.
These seven questions test whether you understand what a lambda is underneath, not only how to write one, and whether you use Optional the way it was designed.
Q26. "What is a functional interface, and why can a lambda be assigned to one?"
Reveal answer
Strong answer A functional interface is an interface with exactly one abstract method. Runnable has run(), Comparator has compare(a, b), Function has apply(x). Such an interface describes "one piece of behaviour", and that is what a lambda is.
A lambda such as c -> c - 5000 has no type of its own. The compiler works out its type from where it is used: the target type. If the target is an interface with one abstract method, the compiler checks that the lambda's parameters and result match that method, and then creates an object of that interface whose single method runs the lambda's body. Assign the same lambda to a different functional interface with a matching shape and it becomes that type instead.
What does not count as abstract: default methods, static methods, and methods that repeat Object's public methods such as equals. That is why Comparator, which lists equals and many default methods, is still functional.
The annotation @FunctionalInterface is optional. It is a check you ask the compiler to make: if someone adds a second abstract method later, the interface stops compiling instead of silently breaking every lambda that used it.
Lambdas are objects, but they are created by the JVM at run time through invokedynamic, not as an Outer$1.class file on disk like an anonymous class.
Picture it A custom functional interface with a default and a static method accepts a lambda; an interface with two abstract methods refuses one.
The setup: Q26_Functional.java declares Discount with one abstract method apply, a default then, a static percent and a redeclared equals. It assigns a lambda and an anonymous class, composes two discounts and prints what the lambda's class looks like. Q26_TwoMethods.java has an interface with two abstract methods and a lambda.
import java.util.*;
import java.util.function.*;
public class Q26_Functional {
@FunctionalInterface
interface Discount {
int apply(int cents); // the ONE abstract method
default Discount then(Discount next) { return c -> next.apply(apply(c)); } // default: allowed
static Discount percent(int p) { return c -> c - c * p / 100; } // static: allowed
boolean equals(Object o); // Object's methods do not count
}
public static void main(String[] args) {
Discount fest = c -> c - 5000; // lambda -> instance of Discount
Discount old = new Discount() { // what the compiler lets you skip writing
public int apply(int cents) { return cents - 5000; }
};
System.out.println(fest.apply(54700) + " " + old.apply(54700));
System.out.println(Discount.percent(10).then(fest).apply(54700));
System.out.println("fest.getClass().isSynthetic() = " + fest.getClass().isSynthetic() + ", interfaces: "
+ Arrays.toString(fest.getClass().getInterfaces()));
Runnable r = () -> System.out.println("Runnable is a functional interface too");
r.run();
Comparator<String> byLen = (a, b) -> a.length() - b.length(); // Comparator has 2 abstract-looking methods
System.out.println(byLen.compare("dosa", "biryani") + " (equals() is an Object method)");
}
}Make the invisible visible: Run the first file, then compile the second.
49700 49700
44230
fest.getClass().isSynthetic() = true, interfaces: [interface Q26_Functional$Discount]
Runnable is a functional interface too
-3 (equals() is an Object method)
$ javac --release 25 Q26_TwoMethods.java
Q26_TwoMethods.java:2: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
Both is not a functional interface
multiple non-overriding abstract methods found in interface Both
Q26_TwoMethods.java:6: error: incompatible types: Both is not a functional interface
Both x = v -> v + 1;
^
multiple non-overriding abstract methods found in interface BothWhat you see: The lambda and the anonymous class both give 49700 for a 54,700-paise order minus 5,000. percent(10).then(fest) gives 44,230. The lambda's class is synthetic (generated at run time) and implements Discount. With two abstract methods, the compiler says "Both is not a functional interface: multiple non-overriding abstract methods found", and it also rejects the annotation.
Why: One abstract method is what makes the shape unambiguous. With two, the compiler would not know which one the lambda body means.
Anonymous class
The object written out in full.
Discount fest = new Discount() {
@Override
public int apply(int cents) {
return cents - 5000;
}
};Lambda
The same object, body only.
Discount fest = cents -> cents - 5000;
// same interface, same method,
// no Outer$1.class on diskThe shift: The method name, return type and class wrapper come from the interface, so only the parameters and body are left to write.
Land it A functional interface has one abstract method, and the compiler uses it as the target type that tells a lambda what it must implement.
- "What happens if two functional interfaces both fit the lambda?"
-
If a method is overloaded so that two parameters accept the same lambda shape, the call can be ambiguous and the compiler refuses. The classic case is
ExecutorService.submit(...), which accepts both aRunnableand aCallable. A lambda() -> foo()that returns a value fitsCallable, and one with a void body fitsRunnable, so most calls resolve. A body that is a call that returns a value can fit both, and then the compiler prefers the one that returns a value.When it cannot decide, you give it a hint: a cast,
(Callable<String>) () -> ..., or an explicit parameter type on the lambda.A related trap is a generic method with several functional-interface overloads (such as the
Comparator.comparingfamily). Use thecomparingInt,comparingLongandcomparingDoublevariants, which avoid the ambiguity and the boxing.If you design an API, avoid overloads that differ only in the functional interface type. Give the methods different names.
- "Is a lambda the same as a method?"
-
No. A method belongs to a class. A lambda is a value: an object you can store in a variable, pass around, return and call later. The lambda's body is compiled into a private method of the enclosing class, but what you hold is the object that points to it.
A lambda can capture variables from the enclosing method (question 28) and then it becomes an object with state. A lambda that captures nothing can be reused: the JVM usually creates one instance and returns it every time.
It also differs in
this. Inside a lambda,thisis the enclosing object. Inside an anonymous class,thisis the anonymous object, which is the main behavioural difference between the two.Think of a lambda as "a method with no name, wrapped in an object so that it can travel".
- "Why does the JDK annotate interfaces with @FunctionalInterface?"
-
For two reasons: documentation and protection. It tells the reader that lambdas are the intended way to implement it. And it makes the compiler reject an accidental second abstract method, which would break every lambda in every user's code the next time they recompile.
Adding the annotation changes nothing at run time. Interfaces without it are still functional if they have one abstract method, and lambdas work with them.
For your own interfaces I recommend the annotation whenever you expect lambdas. A change in a shared library that silently turns a functional interface into a non-functional one is an easy mistake and an expensive one.
It is also a design signal: if you find yourself adding a second abstract method, you are probably describing an object with several behaviours, and an ordinary interface (not a functional one) is the right shape.
- "Can a functional interface be generic or throw checked exceptions?"
-
Yes to both.
Function<T, R>is generic, and your own interface can be too. The abstract method can declare checked exceptions:Callable.call()is declaredthrows Exception, which is exactly the difference fromRunnable.The common frustration is the opposite one. The standard interfaces for streams (
Function,Predicate,Consumer) declare no checked exceptions, so a lambda that calls a method throwingIOExceptionwill not compile, unless you catch it inside the lambda.The usual fix is a small wrapper: define this interface
a throwing function interfaceruns offlineinterface ThrowingFunction<T, R> { R apply(T t) throws Exception; }and a helper that converts it into a
Functionby wrapping the exception in an unchecked one. Or use a plain loop (question 45), where checked exceptions work normally.I avoid hiding I/O inside stream lambdas altogether. Read the data first, then process it with the pipeline.
Q27. "Function, Predicate, Supplier, Consumer — one real use for each, plus the primitive variants."
Reveal answer
Strong answer Four shapes cover most lambdas, and each has a natural place in a pipeline. They are named by what goes in and what comes out.
Function<T, R>takes aTand returns anR. Use inmap:orders.stream().map(Order::totalCents).Predicate<T>takes aTand returns aboolean. Use infilter,removeIf,anyMatch:o -> o.status().equals("DELIVERED").Supplier<T>takes nothing and returns aT. Use for lazy values and factories:Optional.orElseGet(...),Collectors.toCollection(ArrayList::new).Consumer<T>takes aTand returns nothing. Use inforEachandpeek: log, save or print something.
Two-argument and same-type versions: BiFunction<T, U, R> (used by Map.merge and reduce), UnaryOperator<T> (a function from T to T, used by replaceAll) and BinaryOperator<T> (two T in, one T out, used by reduce and toMap merge functions).
Primitive variants avoid boxing. IntPredicate, IntFunction<R>, ToIntFunction<T>, IntUnaryOperator, IntBinaryOperator, IntSupplier and IntConsumer, and the same families for long and double. With IntPredicate a number never becomes an Integer object.
The names tell the shape: ToIntFunction goes from an object to an int, IntFunction from an int to an object.
Picture it All of them, used on the QuickBite orders, with the stream stage each one belongs to.
The setup: Q27_FourKinds.java declares one variable of each interface with a real QuickBite lambda, runs three orders through filter, peek, map and forEach, and then uses four primitive variants.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Q27_FourKinds {
public static void main(String[] args) {
Function<Order, Integer> total = Order::totalCents; // T -> R (map)
Predicate<Order> delivered = o -> o.status().equals("DELIVERED"); // T -> boolean (filter)
Supplier<List<String>> fresh = ArrayList::new; // () -> T (lazy value, factory)
Consumer<Order> log = o -> System.out.println(" saw order " + o.id()); // T -> void (forEach)
BiFunction<Integer, Integer, Integer> add = Integer::sum; // (T, U) -> R (reduce, merge)
UnaryOperator<String> shout = s -> s.toUpperCase(); // T -> T
BinaryOperator<Integer> max = Math::max; // (T, T) -> T
List<Order> first3 = Data.ORDERS.subList(0, 3);
first3.stream().filter(delivered).peek(log).map(total).forEach(System.out::println);
List<String> list = fresh.get(); list.add(shout.apply("raita"));
System.out.println(list + " " + add.apply(2, 3) + " " + max.apply(4, 9));
IntPredicate big = n -> n > 30000; // int -> boolean, no boxing
ToIntFunction<Order> cents = Order::totalCents; // Order -> int
IntFunction<String> label = n -> "#" + n; // int -> String
IntUnaryOperator twice = n -> n * 2; // int -> int
System.out.println(Data.ORDERS.stream().mapToInt(cents).filter(big).count()
+ " big orders, label " + label.apply(7) + ", twice " + twice.applyAsInt(21));
}
}Make the invisible visible: Run it.
saw order 1
54700
saw order 2
29700
[RAITA] 5 9
6 big orders, label #7, twice 42What you see: Delivered orders 1 and 2 passed the predicate. The peek line "saw order 1" printed before order 1's total (54,700), then order 2, which shows that elements move one at a time (question 35). The list, sum and max results follow. Finally the primitive variants counted six orders above ₹300 with no boxing.
Why: Each interface is just a shape for one lambda. Knowing the shape tells you which stream method accepts it: Predicate for filter, Function for map, Consumer for forEach and Supplier for lazy defaults.
| Interface | Shape | Method | Typical use |
|---|---|---|---|
Function<T,R> | T to R | apply | map, computeIfAbsent |
Predicate<T> | T to boolean | test | filter, removeIf |
Supplier<T> | nothing to T | get | orElseGet, factories |
Consumer<T> | T to nothing | accept | forEach, peek |
BiFunction<T,U,R> | T, U to R | apply | Map.merge |
UnaryOperator<T> | T to T | apply | List.replaceAll |
BinaryOperator<T> | T, T to T | apply | reduce, toMap merge |
IntPredicate, ToIntFunction<T> | int to boolean, T to int | test, applyAsInt | IntStream.filter, mapToInt |
Boxed
An object per number.
Function<Integer, Integer> twice =
n -> n * 2;
Predicate<Integer> big =
n -> n > 30000;
// every call boxes and unboxesPrimitive
No boxing.
IntUnaryOperator twice =
n -> n * 2;
IntPredicate big =
n -> n > 30000;
// plain ints all the wayThe shift: The primitive interfaces keep numbers as numbers, which matters when a stream holds millions of them.
Land it The four shapes are Function, Predicate, Supplier and Consumer, matched to map, filter, lazy values and forEach, with Int, Long and Double versions to avoid boxing.
- "Why are there so many functional interfaces?"
-
Because Java generics cannot hold primitives, and because each shape needs a name for its method.
Function<Integer, Integer>boxes every number. To avoid that the JDK adds a separate interface for each primitive combination: about forty injava.util.function.You only ever need to remember the pattern. The prefix says the primitive type (
Int,Long,Double), andToin the name says the result is primitive:ToIntFunctionreturns an int.Bimeans two arguments.Operatormeans argument and result are the same type.The IDE completes the right one when you hover over a method such as
mapToInt.In your own code, resist the urge to create new ones. A custom functional interface is justified when it has a domain name that improves readability, such as
Discountin the previous question, or when it needs a checked exception. - "When would I use Supplier in my own API?"
-
Whenever the value is expensive or may not be needed.
Optional.orElseGet(supplier)only calls it when the Optional is empty (question 30). A logging call such aslog.debug(() -> expensiveDump())avoids building a string when debug is off.Objects.requireNonNull(x, () -> "message " + id)builds the message only on failure.Suppliers also create fresh objects for each use.
Collectors.toCollection(TreeSet::new)passes a supplier, so each group in agroupingBygets its own set. And aSupplier<Stream<T>>is the fix for reusing a stream (question 38).If the argument is cheap and always needed, pass the value itself. A supplier adds a small cost and a little indirection, so use it for the reason of laziness or freshness.
A good design check: if a method takes a
Supplier, its documentation should say when and how many times it is called. - "What is the difference between Consumer and Function returning void?"
-
There is no such thing as a
Functionreturning void. If a method must return something, you useFunction(or aCallable); if it returns nothing, you useConsumer(orRunnablewhen it takes no argument). A lambda body can be written in either style, and the compiler picks the interface from the target type.An example that confuses people:
list.forEach(x -> map.put(x, 1))compiles even thoughputreturns a value, because for aConsumerthe result of an expression statement is discarded.The reverse does not hold:
x -> System.out.println(x)used as aFunctionwould not compile, sinceprintlnreturnsvoidand a function must produce a value.The practical rule:
Consumeris for side effects (print, save, send). If you find yourself wanting one in the middle of amap, usepeekfor debugging only, or restructure. - "How do these relate to method references?"
-
A method reference is a shorter way to write a lambda that just calls one existing method.
Order::totalCentsis the same aso -> o.totalCents(), and it fits aFunction<Order, Integer>or aToIntFunction<Order>, depending on where you use it. The compiler picks the interface from the target.That is why one reference can have different meanings:
String::lengthis aFunction<String, Integer>inmapand aToIntFunction<String>inmapToInt, the second without boxing.Use them when they make the line shorter and clearer. If the lambda does something extra or needs arguments in a different order, write the lambda. Question 29 shows the four kinds.
My rule: use a method reference when the name of the method says what the lambda does, and a lambda when you would otherwise have to explain it.
Q28. "Why must variables captured by a lambda be effectively final?"
Reveal answer
Strong answer A lambda can use local variables from the method around it, for example base in () -> base + 1. The rule is that such a variable must be final or effectively final: never changed after it is first assigned. If you assign to it anywhere, before or after, the compiler reports "local variables referenced from a lambda expression must be final or effectively final".
Why. A lambda may run later, on another thread, after the method has returned and its local variables are gone. So the lambda does not get a link to the variable. It gets a copy of its value at the moment the lambda is created. If the original could change afterwards, there would be two values for one name, and the code would read as if they were the same. The rule removes the confusion by forbidding the change.
It also protects against threads. Local variables live on one thread's stack. A lambda on another thread cannot safely see a variable that the first thread keeps changing, and Java has no volatile for locals. Requiring effectively final makes captured data a plain constant.
Only locals and parameters are restricted. Fields can be changed from a lambda, because the lambda holds a reference to the object and reads the field at run time, which is safe in the usual object-sharing sense (and thread-safety is then your job).
Ways around it when you truly need a changing value: use a stream operation that does the job (count, sum, reduce), or an AtomicInteger if several threads update it, or restructure to avoid mutation.
Picture it The two compile errors, and the working versions: the loop counter copied into a fresh variable, a counter in an AtomicInteger, and no counter at all.
The setup: Q28_Broken.java tries to add to a local sum inside forEach and captures a changing loop variable. Q28_Capture.java shows the correct versions.
import java.util.*;
import java.util.function.*;
public class Q28_Broken {
public static void main(String[] args) {
int total = 0;
List.of(1, 2, 3).forEach(n -> total += n); // lambda tries to write the local
List<Supplier<String>> coupons = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
coupons.add(() -> "coupon-" + i); // i changes every pass
}
}
}Make the invisible visible: Compile the broken file with release 25.
$ javac --release 25 Q28_Broken.java
Q28_Broken.java:7: error: local variables referenced from a lambda expression must be final or effectively final
List.of(1, 2, 3).forEach(n -> total += n); // lambda tries to write the local
^
Q28_Broken.java:11: error: local variables referenced from a lambda expression must be final or effectively final
coupons.add(() -> "coupon-" + i); // i changes every pass
^What you see: Both lambdas are rejected with the same message. One writes to total and the other reads a loop variable i that the loop keeps changing.
The fix: Copy the changing value into a variable that is created fresh on each pass, use an atomic for counting from several threads, or let the stream count for you.
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.*;
public class Q28_Capture {
public static void main(String[] args) {
// 1. the capture rule: a lambda gets a COPY of the local variable
int base = 100;
Supplier<Integer> s = () -> base + 1;
System.out.println(s.get());
// 2. the fixes when you really need a changing number
AtomicInteger counter = new AtomicInteger();
List.of("a", "b", "c").forEach(x -> counter.incrementAndGet());
int[] box = {0}; // a one-slot array also works, but is a smell
List.of("a", "b", "c").forEach(x -> box[0]++);
System.out.println(counter + " " + box[0]);
int count = (int) List.of("a", "b", "c").stream().count(); // best: no mutation at all
System.out.println(count);
// 3. the loop-variable story: one coupon per loop pass
List<Supplier<String>> coupons = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
int copy = i; // new variable every pass, never changes
coupons.add(() -> "coupon-" + copy);
}
coupons.forEach(c -> System.out.print(c.get() + " "));
System.out.println();
}
}101
3 3
3
coupon-1 coupon-2 coupon-3 What you see now: The three counting approaches agree on 3. And each coupon lambda captured its own copy of the loop value, so the output reads coupon-1 coupon-2 coupon-3, where a shared variable would have printed the same number three times.
Does not compile
The lambda writes to a local.
int total = 0;
orders.forEach(o -> {
total += o.totalCents(); // error
});Compiles
Let the stream do the sum.
int total = orders.stream()
.mapToInt(Order::totalCents)
.sum();
// or an AtomicInteger if you mustThe shift: The sum is a result of the pipeline, not a variable that the pipeline pokes from outside.
Land it A lambda captures a copy of a local variable's value, so the compiler requires that the variable never changes; if I need a changing number I let the stream compute it or use an atomic.
- "What was the bug that this rule prevents?"
-
In the anonymous-class days people hit it with loop variables. Suppose a list of coupons is built in a loop, and each coupon's action reads the counter. If the lambda could see the live counter, then by the time the actions run, the loop has finished and every coupon would read the final value. Three coupons, all "coupon-4".
That is the classic closure bug in languages that capture variables by reference, JavaScript's
varin loops for example. Java avoids it by copying the value at creation time and forbidding changes. The compile error is the price, and the cure takes one line:int copy = i;.The version in the demo shows the right result. Each pass creates a new
copy, so each lambda holds its own value.The rule makes a whole category of "wrong variable at wrong time" bugs impossible, at the cost of a slightly longer line sometimes.
- "Is an AtomicInteger or a one-element array a good workaround?"
-
Both work. Neither is a good first choice. A one-element array (
int[] box = {0}) is a trick that gets round the rule because the array reference never changes, only its content. It is not thread-safe, and it tells the reader "I am doing something odd".AtomicIntegeris thread-safe and honest: it says "this number changes, maybe from several threads". Use it for counters across threads, such as counting processed items in a parallel loop or tracking progress.Before you reach for either, ask whether the stream can produce the number:
count(),sum(),reduceandcollectexist for that reason, and they stay correct if you later make the stream parallel (question 42).A counter updated from inside a lambda in a sequential stream still works with the array trick, but it is the pattern that breaks first when someone adds
.parallel(). - "Does the rule apply to fields, and to anonymous classes?"
-
For fields, no. A lambda that uses
this.count++or a static counter is fine for the compiler, because it accesses the field through the object, not through a copied local. Thread-safety becomes your problem, so a shared counter field needs an atomic or a lock.For anonymous and local classes, yes, and the same rule applied even earlier: before Java 8, captured locals had to be declared
final. Java 8 relaxed it to "effectively final", which means you do not need to write the keyword if you never change the variable.For a lambda inside a loop, remember that the enhanced
forvariable (for (var o : orders)) is effectively final in each pass, because each pass declares a new variable. The classicfor (int i...)loop variable is not.So you can capture
ofrom an enhanced for, but notifrom an indexed loop. - "Why not allow lambdas to modify captured variables, like JavaScript does?"
-
The Java designers considered it and decided against it. Allowing it would mean the captured variable cannot live on the stack any more. It would have to be moved to a heap object, shared between the method and the lambda, and then made safe for several threads. That costs memory and speed for every local, and it invites the very concurrency bugs the rest of this chapter is about.
It would also change what a local variable is. Today a local belongs to one thread, always. Capturing by reference would let two threads share a plain local without any synchronisation, which is a data race by design.
The designers preferred a simple and safe rule that costs one extra line at the rare places where you need mutation. A shared mutable thing should look shared: an object, an atomic or a collection.
I find the rule helpful, since it nudges code toward the stream style where results flow out of the pipeline and nothing is poked from inside it.
Q29. "The four kinds of method references — with an example of each."
Reveal answer
Strong answer A method reference is a shorter way to write a lambda that only calls one existing method. The :: separates the thing from the method name. There are four kinds, and the difference is who receives the call.
- Static method:
Class::staticMethod.Integer::parseIntmeanss -> Integer.parseInt(s). The lambda's arguments go straight into the static method. - Bound instance method:
object::method.shop::tagmeansid -> shop.tag(id). The object is fixed when the reference is created, and every call uses that same object.System.out::printlnis the best-known example. - Unbound instance method:
Class::method.String::lengthmeanss -> s.length(). The first argument of the lambda becomes the receiver, and the remaining arguments are passed on.String::compareToIgnoreCasemeans(a, b) -> a.compareToIgnoreCase(b). - Constructor:
Class::new.ArrayList::newmeans() -> new ArrayList<>()orn -> new ArrayList<>(n), depending on the target type. Arrays work too:Integer[]::new.
The tricky one is the second versus the third, because both look like something::method. The test: if the left side is a class name, the first lambda argument is the receiver (unbound). If the left side is a variable or expression, that object is the receiver (bound).
When the compiler cannot decide which kind you meant, because a class has both a static and an instance method with the same name, it reports an ambiguity error. Write the lambda then.
Picture it One program shows all four kinds with the equivalent lambda beside it, and a sorted-names pipeline uses two of them.
The setup: Q29_MethodRefs.java defines a static method tax and an instance method tag, builds a reference of each kind, prints the results and then uses Order::customer, String::compareToIgnoreCase and LinkedList::new in one pipeline.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Q29_MethodRefs {
static int tax(int cents) { return cents / 20; } // a static method
final String prefix = "order-";
String tag(int id) { return prefix + id; } // an instance method
public static void main(String[] args) {
// 1. static method: Class::staticMethod
IntUnaryOperator a = Q29_MethodRefs::tax;
// 2. bound instance method: object::method (the object is fixed NOW)
Q29_MethodRefs shop = new Q29_MethodRefs();
IntFunction<String> b = shop::tag;
// 3. unbound instance method: Class::method (first argument becomes the receiver)
Function<String, Integer> c = String::length;
// 4. constructor: Class::new
Supplier<List<String>> d = ArrayList::new;
Function<String, StringBuilder> e = StringBuilder::new;
System.out.println(a.applyAsInt(54700) + " " + b.apply(7) + " " + c.apply("biryani")
+ " " + d.get() + " " + e.apply("raita").reverse());
// the same four as lambdas, for comparison
System.out.println(((IntUnaryOperator) x -> Q29_MethodRefs.tax(x)).applyAsInt(54700));
LinkedList<String> customers = Data.ORDERS.stream().map(Order::customer).distinct()
.sorted(String::compareToIgnoreCase).collect(Collectors.toCollection(LinkedList::new));
System.out.println(customers);
System.out.println(Stream.of("a", "b").map(String::toUpperCase).toList());
System.out.println(Stream.of(1, 2, 3).toArray(Integer[]::new).length + " (array constructor ref)");
}
}Make the invisible visible: Run it.
2735 order-7 7 [] atiar
2735
[asha, kiran, meera, ravi]
[A, B]
3 (array constructor ref)What you see: tax turned 54,700 into 2,735 (5 per cent), the bound reference shop::tag produced order-7, the unbound String::length returned 7 for "biryani", and the constructor references made an empty list and a reversed StringBuilder ("atiar"). The pipeline sorted four customer names into a LinkedList.
Why: Each reference is a lambda in disguise. Knowing which of the four it is tells you where the receiver comes from.
| Kind | Written | Same as lambda |
|---|---|---|
| Static | Integer::parseInt | s -> Integer.parseInt(s) |
| Bound instance | shop::tag | id -> shop.tag(id) |
| Unbound instance | String::length | s -> s.length() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
Lambda
Spell the call out.
orders.stream()
.map(o -> o.customer())
.filter(s -> !s.isBlank())
.forEach(s -> System.out.println(s));Method references
Name the method only.
orders.stream()
.map(Order::customer)
.filter(Predicate.not(String::isBlank))
.forEach(System.out::println);The shift: When the lambda only forwards its arguments, naming the method says the same thing in fewer words.
Land it The four kinds are static, bound instance, unbound instance and constructor, and the left side of the double colon tells me who receives the call.
- "What is the difference between a bound and an unbound reference in practice?"
-
A bound reference captures the object at the moment it is created.
logger::infoalways callsinfoon that exact logger, even if the variableloggeris later reassigned (and it cannot be, because it must be effectively final). Creating the reference evaluates the left side once, and if that isnull, it throwsNullPointerExceptionimmediately, not when the reference is used.An unbound reference is told its receiver on each call:
String::lengthis used with a different string every time, supplied as the first argument. It does not capture anything, so the JVM can reuse the same object.The bound one is a closure (it carries data). The unbound one is a plain function.
A reliable test is to ask "where does the receiver come from". If it is the thing before
::, it is bound. If it is the stream element, it is unbound. - "When should I prefer a lambda to a method reference?"
-
When the reference is longer or less clear than the lambda.
o -> o.totalCents() > 30000has a condition, so it cannot be a reference.x -> foo(x, 2)passes an extra argument, so it cannot be one either. A reference to a method with many overloads is hard to read, because the reader must work out which overload the target type selects.Another reason is debugging and stack traces. A lambda in a stack trace shows as
lambda$main$0, and a method reference shows up as the target method plus a hidden frame, so it is not worse, but a named method is easier to find.Also, IDEs may offer to convert either way. I follow the rule of thumb: if the lambda is a single call with the same arguments in the same order, use a reference, otherwise leave the lambda.
Do not chase the shortest form. The aim is that a reader sees the intent in one glance.
- "How does Class::method pick between a static and an instance method?"
-
The compiler tries both readings against the target type. For
Function<String, Integer>andInteger::toString, it finds the staticInteger.toString(int)and the instanceInteger.toString(), and both fit, so the reference is ambiguous and does not compile. The same ambiguity exists forInteger::toHexString-style pairs in other classes.The fix is a lambda that makes the choice visible:
i -> Integer.toString(i)ori -> i.toString().It rarely happens in everyday code, but when it does the compiler's message is clear: "reference to toString is ambiguous". Treat it as a prompt to write the lambda.
Another quiet trap:
Object::toStringandString::valueOfbehave differently fornull.String::valueOfreturns "null" whileObject::toStringthrows. Choose by what you want for nulls. - "What are constructor references useful for in practice?"
-
Three places show up all the time. First,
Collectors.toCollection(TreeSet::new)andgroupingBy(f, TreeMap::new, ...)choose which collection or map to build. Second,Optional.orElseGet(ArrayList::new)andcomputeIfAbsent(key, k -> new ArrayList<>())create a value only when needed. Third,stream.toArray(String[]::new)creates a typed array of the right length.The same reference can mean different constructors depending on the target.
ArrayList::newas aSuppliercalls the no-argument constructor, and as aFunction<Integer, List>calls the one that takes a capacity.For records and value classes,
Line::newcan feedmapwith the right arity: with a two-argument constructor it fits aBiFunction.One caveat: a constructor reference to an inner (non-static) class needs the outer instance, which is awkward, and a reason to make helper classes static or records.
Q30 · Scenario. "orElse(loadFromDatabase()) runs the query every time, even when the Optional has a value. Why?"
Reveal answer
Strong answer Because of how Java calls methods, not because of Optional. Java evaluates every argument before it calls the method. In cached.orElse(loadFromDatabase()), the call loadFromDatabase() is an argument. It runs first, and its result is handed to orElse. Only then does orElse look inside the Optional and decide it does not need the value. The database was already queried.
The fix is orElseGet, which takes a Supplier: cached.orElseGet(() -> loadFromDatabase()) or orElseGet(this::loadFromDatabase). You pass a recipe, not a result. orElseGet runs the recipe only when the Optional is empty.
Rule: orElse is for a value you already have (a constant, a variable, a cheap literal). orElseGet is for anything that costs time, touches a database or network, allocates something big, has side effects or can throw.
The same problem exists outside Optional. Any API that takes a plain value where a supplier would be lazy has it: map.getOrDefault(key, expensive()) computes the default every time, and computeIfAbsent(key, k -> expensive()) is the lazy one.
A related choice: orElseThrow(() -> new NotFoundException(...)) builds the exception only when needed, which also avoids constructing a stack trace for nothing.
Picture it A counter shows exactly when the "database" is called under orElse, orElseGet and an empty Optional with orElseGet.
The setup: Q30_OrElse.java has a fake loadFromDatabase() that prints a line and counts its calls. The Optional holds a cached menu in the first two cases.
import java.util.*;
public class Q30_OrElse {
static int dbCalls = 0;
static String loadFromDatabase() {
dbCalls++;
System.out.println(" ...querying the database (call #" + dbCalls + ")");
return "default-menu";
}
public static void main(String[] args) {
Optional<String> cached = Optional.of("cached-menu");
System.out.println("orElse:");
String a = cached.orElse(loadFromDatabase()); // argument is evaluated BEFORE orElse runs
System.out.println(" got " + a + ", db calls so far " + dbCalls);
System.out.println("orElseGet:");
String b = cached.orElseGet(Q30_OrElse::loadFromDatabase); // supplier runs only when empty
System.out.println(" got " + b + ", db calls so far " + dbCalls);
System.out.println("empty + orElseGet:");
String c = Optional.<String>empty().orElseGet(Q30_OrElse::loadFromDatabase);
System.out.println(" got " + c + ", db calls so far " + dbCalls);
System.out.println("orElseThrow:");
try { Optional.<String>empty().orElseThrow(() -> new NoSuchElementException("menu missing")); }
catch (NoSuchElementException e) { System.out.println(" " + e.getMessage()); }
}
}Make the invisible visible: Run it.
orElse:
...querying the database (call #1)
got cached-menu, db calls so far 1
orElseGet:
got cached-menu, db calls so far 1
empty + orElseGet:
...querying the database (call #2)
got default-menu, db calls so far 2
orElseThrow:
menu missingWhat you see: With orElse, the line "...querying the database (call #1)" printed even though the answer was cached-menu. With orElseGet on the same full Optional, nothing was queried and the count stayed at 1. With an empty Optional and orElseGet, the query ran once (call #2), as it should.
Why: The method call in the argument position happens before the callee starts. A supplier moves the call inside, where orElseGet can decide.
orElse
The query is an argument.
String menu = cached.orElse(
loadFromDatabase()); // runs first
// db call even when cached has a valueorElseGet
The query is a recipe.
String menu = cached.orElseGet(
() -> loadFromDatabase());
// db call only when cached is emptyThe shift: One method reference or lambda turns "the result of the call" into "the call, if needed".
Land it Java evaluates arguments before the call, so orElse always runs the query; orElseGet takes a Supplier and runs it only when the Optional is empty.
- "Is orElse ever the right choice?"
-
Yes, when the fallback is already a value.
name.orElse("unknown")andcount.orElse(0)cost nothing to compute, so they are simple and clear. Wrapping a literal in a lambda adds noise for no benefit.It also matters if the fallback is a variable that you have already computed for another reason. Then there is no extra work to save.
Static analysis tools (IntelliJ, SonarQube, Error Prone) flag
orElse(methodCall())as a possible performance bug for exactly this reason, and they stay quiet for literals and variables. Listen to the tool when it speaks.My rule is mechanical: if the argument contains a method call or
new, think aboutorElseGet. If it is a literal, a constant or an existing variable, useorElse. - "Does orElse have effects besides cost?"
-
Yes: side effects and exceptions. If the argument method writes a log line, increments a metric, saves a default row or throws when something is missing, all of that happens on every call, even when the Optional is full. The demo's printed line is the visible version of that.
A real bug I have seen:
repo.find(id).orElse(repo.save(new Customer(id)))created and saved a new customer on every lookup, whether or not one existed. The data was wrong, and nothing crashed.The corrected version is
repo.find(id).orElseGet(() -> repo.save(new Customer(id))). Or, clearer in many cases, an explicitifwithifPresentOrElse.That is why this question is a favourite: the wrong code looks harmless, runs correctly in tests with an empty database, and misbehaves in production.
- "How does orElseThrow relate to these?"
-
orElseThrow(Supplier)takes a supplier too, so the exception is created only when the Optional is empty. That matters because creating an exception fills in a stack trace, which is slow.orElseThrow(() -> new NotFoundException(id))creates nothing for the common case.Java 10 added a no-argument
orElseThrow()that throwsNoSuchElementException. It does the same asget()but the name says what it does, so prefer it toget()when you accept that exception. IDEs warn aboutget()without a check for that reason.For a REST service, the usual pattern is this:
the usual REST patternruns offlinefindById(id) .orElseThrow(() -> new ResponseStatusException(NOT_FOUND))The exception turns into a 404 response.
So the family is:
orElse(value),orElseGet(supplier)andorElseThrow(supplier). The last two are lazy. - "How do I spot this in code review or tests?"
-
In review, scan for
orElse(followed by a method call. Most IDEs highlight it. In tests, count the calls: give the fake repository or service a counter, assert it equals zero for a cache hit, as the demo's counter does. A test that checks "the database is not called when the cache has the value" would have caught the bug.A cheap team rule is to ban
orElsewith a method call in code review, and to add the inspection to the shared IDE profile or to the static analysis build.It is also a good reason to log at the data-access layer. A graph of queries per request makes an accidental extra query visible long before a customer notices.
The same technique finds the related bug in
getOrDefaultand inObjects.requireNonNullElse(x, expensive()), where the lazy version isrequireNonNullElseGet.
Q31. "How should Optional be used — and where should it never appear?"
Reveal answer
Strong answer Optional<T> was designed for one job: a return type that says "there may be no result". It makes the missing case part of the method's signature. Optional<Customer> find(int id) forces the caller to decide what to do when nobody is found, which a plain null never does.
Use it by chaining instead of unwrapping. map transforms the value if present, flatMap does the same when the function itself returns an Optional, filter keeps it only if a condition holds, or (Java 9) offers another Optional, orElse, orElseGet and orElseThrow end the chain with a plain value, and ifPresentOrElse (Java 9) runs one of two actions. stream() (Java 9) turns it into a stream of zero or one element, which is the clean way to flatten a list of Optionals.
Never use it for: fields (it is not Serializable, and it adds an object per value), method parameters (callers would have to wrap values, and null can still be passed), collection elements (List<Optional<T>> is a list with holes, so filter instead), and as a replacement for every null (a simple internal null check is fine).
Never do: Optional.of(null) (it throws; use ofNullable), opt.get() without checking (it throws NoSuchElementException), or if (opt.isPresent()) return opt.get();, which is a null check with extra steps. Use map and orElse instead.
For primitives there are OptionalInt, OptionalLong and OptionalDouble, returned by max(), average() and friends.
Picture it A customer lookup with an optional phone number, handled by chaining, plus the three mistakes in a row.
The setup: Q31_Optional.java has a database map where one customer has no phone. find returns an Optional, phone chains map, and the main method shows filter, flatMap, ifPresentOrElse, or and stream. Then it triggers Optional.of(null), get() on empty and the nested-Optional trap.
import java.util.*;
public class Q31_Optional {
record Customer(String name, String phone) {} // phone may be absent
static final Map<Integer, Customer> DB = Map.of(1, new Customer("asha", "98450"), 2, new Customer("ravi", null));
static Optional<Customer> find(int id) { return Optional.ofNullable(DB.get(id)); } // return type: good
static Optional<String> phone(int id) { return find(id).map(Customer::phone); } // map: null -> empty
public static void main(String[] args) {
System.out.println(phone(1) + " " + phone(2) + " " + phone(3));
System.out.println(find(1).map(Customer::name).filter(n -> n.startsWith("a")).orElse("?"));
find(2).flatMap(c -> Optional.ofNullable(c.phone())).ifPresentOrElse(
p -> System.out.println("call " + p), () -> System.out.println("no phone, send SMS later"));
System.out.println(find(3).or(() -> find(1)).get().name());
System.out.println(find(1).stream().count() + " " + find(3).stream().count());
System.out.println(find(3).isEmpty() + " " + find(1).isPresent());
try { Optional.of(null); } catch (NullPointerException e) { System.out.println("Optional.of(null) -> NPE"); }
try { find(3).get(); } catch (NoSuchElementException e) { System.out.println("get() on empty -> " + e.getMessage()); }
try { find(3).orElseThrow(); } catch (NoSuchElementException e) { System.out.println("orElseThrow() -> same exception, clearer name"); }
Optional<Optional<String>> nested = find(1).map(c -> Optional.of(c.name())); // map when you needed flatMap
System.out.println("nested: " + nested);
Optional<String> nullInside = Optional.of("x");
System.out.println("Optional is not Serializable: " + ((Object) nullInside instanceof java.io.Serializable));
System.out.println("equals: " + Optional.of("a").equals(Optional.of("a")));
}
}Make the invisible visible: Run it.
Optional[98450] Optional.empty Optional.empty
asha
no phone, send SMS later
asha
1 0
true true
Optional.of(null) -> NPE
get() on empty -> No value present
orElseThrow() -> same exception, clearer name
nested: Optional[Optional[asha]]
Optional is not Serializable: false
equals: trueWhat you see: A missing customer and a missing phone both give Optional.empty, so the caller deals with one shape. ifPresentOrElse picked its second branch for ravi, who has no phone. Optional.of(null) threw a NullPointerException; get() on empty threw NoSuchElementException: No value present. Calling map with a function that returns an Optional produced Optional[Optional[asha]], which is why flatMap exists. And the check printed false: Optional is not Serializable.
Why: Every step either carries the value forward or carries "nothing" forward. Nothing has to be checked in the middle.
null checks
Nested ifs, easy to miss one.
String phone = null;
Customer c = repo.find(id);
if (c != null) {
phone = c.phone();
}
if (phone == null) phone = "none";Optional
One chain, one fallback.
String phone = repo.find(id)
.map(Customer::phone)
.orElse("none");
// find returns Optional<Customer>The shift: The absence is handled once, at the end of the chain, and the type says the value may be missing.
Land it Optional is for return values that may be absent, used by chaining map, filter and orElse, and never for fields, parameters or collections.
- "Why not use Optional for fields and parameters?"
-
For a field, it costs an extra object for every value, it is not
Serializable(so it breaks Java serialisation and some frameworks), and it still allows the field itself to benull, which defeats the purpose. A plain nullable field with a getter that returns an Optional gives the caller the safe API and keeps the object small.For a parameter, it forces every caller to write
Optional.of(x)orOptional.empty()and it creates an extra object just to pass nothing. And the callee still has to check that the Optional itself is not null. An overloaded method (one with and one without the argument) is clearer.The authors of the API said the same: Brian Goetz wrote that Optional was meant for "return values where there is a clear need to represent no result". It is not a general-purpose Maybe type.
There is one place where teams relax the rule: records and DTOs that map JSON with optional fields. Even there I prefer a nullable component and an accessor that returns an Optional.
- "What is the difference between map and flatMap on Optional?"
-
map(f)appliesfto the value and wraps the result in an Optional. Iffitself returns an Optional, you get an Optional inside an Optional.flatMap(f)expectsfto return an Optional and does not wrap it again, so you get a single layer.In the demo,
find(1).map(c -> Optional.of(c.name()))gaveOptional[Optional[asha]], andflatMapwould have givenOptional[asha]. A practical case:find(id).flatMap(c -> Optional.ofNullable(c.phone())), where the next step may itself find nothing.A short test: if your lambda returns a plain value, use
map; if it returns an Optional, useflatMap. The compiler's type error (an Optional of Optional) is the usual reminder.The same difference exists for streams, as question 39 shows.
- "Is get() really that bad?"
-
It is not wrong, but it is an unchecked bomb.
get()throwsNoSuchElementExceptionwhen empty, and nothing in the code explains why you believed it was present. Reviewers and static analysis tools flag it for that reason.When you really expect a value and an absence would be a bug, say so:
orElseThrow()(Java 10) does exactly whatget()does with a clear name, and this form adds a message that helps whoever reads the log:orElseThrow with a messageruns offlineorElseThrow(() -> new IllegalStateException("customer " + id + " missing"))The one acceptable use of
get()is directly after a check in a short scope, and even thenifPresentormapreads better. In tests,get()is common and fine.The name
getwas a design regret; the JDK team has saidorElseThrow()is the preferred spelling. - "How does Optional compare with returning null or throwing?"
-
All three signal "not found", and they suit different cases. Null is cheap, invisible in the signature and the source of the most common Java bug. An exception says "this should not have happened" and is right when absence is a bug or an unrecoverable error, such as a missing configuration value. Optional says "absence is a normal outcome": looking up a user by email, a cache lookup, a first match in a list.
For collections, return an empty collection, never null and never an Optional of a collection. An empty list is the natural "nothing" for a list.
For performance-sensitive inner loops, Optional allocates an object per call (the JIT can often remove it with escape analysis, but not always), so inside a hot loop a null check with a clear comment is acceptable.
Choose by meaning: Optional when absence is expected and the caller must decide, exception when it is a bug, empty collection for lists.
Q32. "How do andThen, compose and Predicate.not build bigger functions from small ones?"
Reveal answer
Strong answer The functional interfaces carry default methods that combine one lambda with another into a new lambda. That lets you keep each piece small and name it, then join them.
Function.andThen(g) runs this function first, then g: f.andThen(g).apply(x) is g(f(x)). Function.compose(g) runs g first, then this function: f.compose(g).apply(x) is f(g(x)). The order is the only difference, and it is easy to reverse by mistake. I remember it as "andThen reads left to right like a pipeline; compose reads the way maths writes it".
Predicate has and, or and negate, which combine tests: delivered.and(inBengaluru). Predicate.not(p) (Java 11) is a static helper that works with a method reference: filter(Predicate.not(String::isBlank)) reads clearly, where String::isBlank.negate() does not compile because a method reference has no type on its own.
Others: Consumer.andThen runs two consumers in turn, Comparator.thenComparing adds a tie-breaker to a sort, and BiFunction.andThen transforms the result. Function.identity() is the "do nothing" function you pass to toMap or groupingBy.
These combinators short-circuit like the operators they are named after: a.and(b) never calls b if a is false.
Picture it A price pipeline built from two small functions in both orders, a combined predicate on real orders and a three-level sort.
The setup: Q32_Compose.java defines addTax (+5 per cent) and minus50 (a coupon). It applies them with andThen and compose to 54,700 paise. It then counts QuickBite orders with and, or, negate and Predicate.not, and sorts by city then by total, descending.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Q32_Compose {
public static void main(String[] args) {
Function<Integer, Integer> addTax = c -> c + c / 20; // +5 %
Function<Integer, Integer> minus50 = c -> c - 5000; // coupon
System.out.println("addTax.andThen(minus50) : " + addTax.andThen(minus50).apply(54700)); // addTax first
System.out.println("addTax.compose(minus50) : " + addTax.compose(minus50).apply(54700)); // minus50 first
Predicate<Order> delivered = o -> o.status().equals("DELIVERED");
Predicate<Order> blr = o -> o.city().equals("Bengaluru");
Predicate<Order> big = o -> o.totalCents() > 30000;
System.out.println(count(delivered.and(blr)) + " delivered in Bengaluru");
System.out.println(count(delivered.or(big)) + " delivered or big");
System.out.println(count(delivered.negate()) + " not delivered (negate)");
System.out.println(count(Predicate.not(delivered)) + " not delivered (Predicate.not)");
List<String> words = Arrays.asList("raita", " ", "", "dosa", " ");
System.out.println(words.stream().filter(Predicate.not(String::isBlank)).toList()); // reads clearly
Consumer<String> log = s -> System.out.print("[log " + s + "] ");
Consumer<String> save = s -> System.out.println("[save " + s + "]");
log.andThen(save).accept("order-7");
Comparator<Order> byCity = Comparator.comparing(Order::city);
Comparator<Order> cmp = byCity.thenComparing(Order::totalCents, Comparator.reverseOrder());
System.out.println(Data.ORDERS.stream().sorted(cmp).limit(3).map(o -> o.city() + ":" + o.totalCents()).toList());
}
static long count(Predicate<Order> p) { return Data.ORDERS.stream().filter(p).count(); }
}Make the invisible visible: Run it.
addTax.andThen(minus50) : 52435
addTax.compose(minus50) : 52185
5 delivered in Bengaluru
11 delivered or big
4 not delivered (negate)
4 not delivered (Predicate.not)
[raita, dosa]
[log order-7] [save order-7]
[Bengaluru:68700, Bengaluru:54700, Bengaluru:46900]What you see: addTax.andThen(minus50) gives 52,435: tax first (57,435), then the coupon. addTax.compose(minus50) gives 52,185: coupon first (49,700), then tax. A different order is a different price. The predicates found 5 delivered orders in Bengaluru, 11 delivered-or-big, and 4 not delivered by both negate and Predicate.not. The sort listed the three most expensive Bengaluru orders first.
Why: Each small lambda has a name and can be tested alone. The combinators decide the order, so the order is written once, in one place.
Inline
One long lambda doing it all.
orders.stream()
.filter(o -> o.status().equals("DELIVERED")
&& o.city().equals("Bengaluru")
&& !o.customer().isBlank())
.toList();Composed
Small named pieces.
Predicate<Order> ok =
delivered.and(blr).and(named);
orders.stream().filter(ok).toList();
// each piece testable on its ownThe shift: Naming each condition gives you small testable parts and a final line that reads like a sentence.
Land it andThen runs this function then the next, compose runs the next first, and Predicate and, or and not join small conditions into readable bigger ones.
- "How do I remember andThen versus compose?"
-
Think of the pipeline direction.
f.andThen(g)reads "f, and then g", so data flows through f first.f.compose(g)reads "f composed with g", as in mathematics where(f ∘ g)(x)meansf(g(x)): g runs first. If you are building a pipeline from left to right, you almost always wantandThen.The demo shows the cost of mixing them up: 52,435 against 52,185 paise. A 250-paise difference (₹2.50) per order is the kind of discrepancy that survives code review because both versions look reasonable.
A practical aid is to write a unit test with a non-commutative pair like "add tax" and "subtract coupon", whose result changes if the order is wrong, and keep it as documentation of the intended order.
I use
composerarely. When I do, it is to adapt an existing function to a different input type:length.compose(Person::name)turns a function on strings into one on people. - "Why does String::isBlank.negate() not compile?"
-
A method reference has no type of its own. The compiler gives it a type from the context, such as the parameter type of a method it is passed to. In
String::isBlank.negate()there is no context, sincenegateis being called on the reference itself, so the compiler does not know which functional interface it is.You can give it one with a cast:
((Predicate<String>) String::isBlank).negate(), which is too ugly to use. That is exactly why Java 11 addedPredicate.not(String::isBlank): the argument position gives the reference a target type.The same limit applies to lambdas:
(s -> s.isEmpty()).negate()fails for the same reason. Assign the lambda to a typed variable first, or pass it to a method that supplies the type.So the choices are a typed variable (
Predicate<String> blank = String::isBlank;),Predicate.notor an explicit lambdas -> !s.isBlank(). All three are fine. - "How does Comparator composition work?"
-
Comparator.comparing(keyExtractor)builds a comparator from a function.thenComparingadds a tie-breaker that is used only when the first comparator says two items are equal.reversed()flips the whole comparator, andComparator.reverseOrder()is the natural order reversed.The demo sorts by city and then by total, descending:
the two-level comparatorruns offlinecomparing(Order::city) .thenComparing(Order::totalCents, Comparator.reverseOrder())It lists the Bengaluru orders highest first because the second comparator takes over inside each city.
Watch the placement of
reversed():a.thenComparing(b).reversed()flips both, whilea.thenComparing(b, reverseOrder())flips only the second. Use the second form when you want to reverse one level.Use
comparingInt,comparingLongandcomparingDoublefor primitives to avoid boxing, andnullsFirstornullsLastwhen keys can be null. - "Is there a cost to chaining many small functions?"
-
Each combinator creates a new lambda object that calls the previous ones, so a chain of ten
andThencalls is ten nested calls. For something like pricing, validation or sorting that runs thousands of times, the JIT compiler inlines small lambdas and the cost is usually invisible. For code that runs hundreds of millions of times in a tight loop, measure it, and consider a plain method.Build the combined function once and reuse it. Creating the chain inside a loop wastes allocations. Keep it in a
static finalfield or as a variable outside the loop.Readability can suffer too. A chain of six
andThencalls is harder to debug than three named steps in a method with intermediate variables. In a debugger, a stack trace through combinators shows several generic frames.I compose two or three pieces, and if the chain grows beyond that I write a small named method.
These thirteen questions are about what actually happens between stream() and the result: when code runs, in what order, what is remembered, and what a stream may or may not do.
Q33. "What are the three parts of a stream pipeline, and what does each do?"
Reveal answer
Strong answer Every stream pipeline has the same three parts, in the same order.
The source supplies the elements: list.stream(), Stream.of(...), IntStream.range(...), Files.lines(path), Stream.iterate(...). Creating a source does not read any data. It makes a stream object that knows where the data lives.
Zero or more intermediate operations describe what to do: filter, map, flatMap, sorted, distinct, limit, peek and others. Each returns a new stream. They are lazy: calling them records a step and does no work.
Exactly one terminal operation starts the work and produces a result or an effect: collect, toList, forEach, count, sum, reduce, findFirst, anyMatch. It pulls elements from the source through the recorded steps. After it returns, the stream is used up and cannot be used again (question 38).
A stream is not a collection. It stores nothing, it may be infinite, and it is consumed once. It is a one-shot description of a computation over a source.
That is why a missing terminal operation is a classic bug: the code looks busy and does nothing at all.
Picture it A pipeline built one stage at a time, with a print after each stage to show that nothing has run until the terminal operation.
The setup: Q33_Pipeline.java builds a source, adds a filter and a map as separate variables, prints a message, and only then calls reduce. The same pipeline is then written as one expression with the three parts commented. Finally it prints the class of the stream objects.
import java.util.*;
import java.util.stream.*;
public class Q33_Pipeline {
public static void main(String[] args) {
Stream<Order> source = Data.ORDERS.stream(); // 1. SOURCE: just a recipe holder
Stream<Order> delivered = source.filter(o -> o.status().equals("DELIVERED")); // 2. INTERMEDIATE: returns a new Stream
Stream<Integer> totals = delivered.map(Order::totalCents); // still nothing has run
System.out.println("built the pipeline, nothing printed yet");
int sum = totals.reduce(0, Integer::sum); // 3. TERMINAL: pulls elements, produces a result
System.out.println("revenue " + sum / 100.0);
// the same thing as one expression, with the parts labelled
double rupees = Data.ORDERS.stream() // source
.filter(o -> o.status().equals("DELIVERED")) // intermediate (stateless)
.mapToInt(Order::totalCents) // intermediate
.sum() / 100.0; // terminal
System.out.println("same, one expression: " + rupees);
List<Class<?>> kinds = List.of(Data.ORDERS.stream().getClass(), Data.ORDERS.stream().filter(o -> true).getClass());
kinds.forEach(k -> System.out.println("stream object: " + k.getName()));
}
}Make the invisible visible: Run it.
built the pipeline, nothing printed yet
revenue 3244.0
same, one expression: 3244.0
stream object: java.util.stream.ReferencePipeline$Head
stream object: java.util.stream.ReferencePipeline$2What you see: The message "built the pipeline, nothing printed yet" came before any work. The result, 3,244 rupees of delivered revenue, appeared only after reduce. Both ways gave the same number. The class names show the structure: the source is a Head and each added step is another pipeline stage object.
Why: Each stage is a small object that points to the one before it. The terminal operation walks back to the source and asks for elements one by one.
Described
Intermediate steps, nothing runs.
var s = orders.stream()
.filter(o -> o.id() > 3)
.map(Order::totalCents);
// nothing has been read yetExecuted
A terminal operation starts it.
int sum = orders.stream()
.filter(o -> o.id() > 3)
.mapToInt(Order::totalCents)
.sum(); // terminal: runs nowThe shift: Everything before the terminal operation is a recipe; the terminal operation is the cook.
Land it A pipeline is a source, lazy intermediate steps that return new streams, and one terminal operation that pulls the elements through and uses the stream up.
- "What counts as intermediate and what counts as terminal?"
-
If the method returns a
Stream, it is intermediate. That coversfilter,map,mapToInt,flatMap,distinct,sorted,peek,limit,skip,takeWhile,dropWhileandgather. If it returns something else (a value, a collection,voidor anOptional), it is terminal. That coverscollect,toList,reduce,count,min,max,sum,forEach,findFirst,anyMatchanditerator.A second split cuts across the first: some intermediate operations are stateless (
filter,map) and some are stateful (sorted,distinct), as question 37 shows.A quick check in an IDE: hover over the call and see the return type. A
Stream<...>means you are still describing. Anything else means you started the engine.If your code has no terminal operation, most IDEs flag the unused result of an intermediate call.
- "Why did the designers make streams lazy?"
-
For efficiency and for the infinite case. If every step ran fully before the next began,
filterwould build a whole intermediate list, thenmapwould build another, and so on. Lazy, element-at-a-time execution needs no intermediate lists and can stop early:findFirstafter a million-elementfiltermay look at only three elements.Laziness also makes the infinite streams possible:
Stream.iterate(1, i -> i + 1)never ends, yet.limit(5)works because only five elements are ever pulled.The price is that the code you write does not run where you write it. A
peekor amapwith a side effect fires later, at the terminal operation, and possibly never, or possibly fewer times than the list's size.So treat a pipeline as a description. Do not rely on any particular side effect happening inside it (question 42).
- "Can I have more than one terminal operation, or keep the stream for later?"
-
No. After the terminal operation the stream is closed, and any further use throws this:
the exceptionruns offlineIllegalStateException: stream has already been operated upon or closedThe same happens if you try to attach two terminal operations to one stream variable.
If you need several results from the same data, you have three honest choices: keep the source (a list) and create a new stream for each result; keep a
Supplier<Stream<T>>; or compute everything in one pass with a collector such asteeing(question 49) orsummarizingInt.Streams made from I/O (
Files.lines,BufferedReader.lines) hold an open file and need closing: put them in try-with-resources.Think of a stream as a tap, not a bucket. Water comes out once.
- "Is a stream the same as an Iterator?"
-
They are close cousins, with a different job. An
Iteratorhands out elements one at a time to your own loop. A stream takes a recipe and runs the whole loop itself, internally, which lets it do things an iterator cannot: it can split the source and process halves on several threads, it can fuse several steps into one pass, and it can skip work it can prove is unnecessary.The internal machinery uses a
Spliterator, the splittable iterator that parallel streams cut in halves (question 55). A stream can give you anIterator(stream.iterator()) when you need to hand elements to old code, which is a terminal operation.The main practical difference is control. With an iterator you decide when to stop and what to remember. With a stream you describe the result, and the library decides how to compute it.
That trade is what makes streams short, and also what makes them hard to debug step by step.
Q34. "Prove that streams are lazy: what runs when there is no terminal operation?"
Reveal answer
Strong answer Nothing runs. The intermediate steps are only recorded. A pipeline like orders.stream().peek(print).map(Order::totalCents) with no terminal operation does not call print once, not even for the first element. You can prove it by putting a peek that prints into the pipeline: no output means no execution.
When a terminal operation is added, the work starts and runs only as far as the terminal operation needs. findFirst stops at the first match. In the demo, a filter for a cancelled order stops after order 3, so only three peek lines print out of twelve orders.
There is one surprise worth knowing: since Java 9, count() may skip the pipeline entirely when the stream knows its own size. For list.stream().peek(...).count() the size of the list is already known and no peek runs. A filter breaks that knowledge, so it must look at each element again.
That is a documented behaviour (the Javadoc says an implementation may skip the pipeline when it can compute the count directly from the source), and it is why you should never put important side effects in peek or map.
Proof in four runs: no terminal prints nothing, findFirst prints three, count without filter prints nothing, and count with a filter looks at everything.
Picture it Four small experiments on the same twelve orders, each printing what the pipeline actually ran.
The setup: Q34_Lazy.java adds a peek that prints the order id into each pipeline, so every execution is visible. It runs a pipeline with no terminal operation, one with findFirst, and two with count.
import java.util.stream.*;
public class Q34_Lazy {
public static void main(String[] args) {
System.out.println("-- no terminal operation:");
Data.ORDERS.stream()
.peek(o -> System.out.println(" peek order " + o.id()))
.map(Order::totalCents); // nothing at all is printed
System.out.println("(nothing ran)");
System.out.println("-- add findFirst (short-circuiting terminal):");
var first = Data.ORDERS.stream()
.peek(o -> System.out.println(" peek order " + o.id()))
.filter(o -> o.status().equals("CANCELLED"))
.findFirst();
System.out.println("found order " + first.get().id() + " after looking at 3 of 12");
System.out.println("-- count() can skip the pipeline entirely (JDK 9+):");
long n = Data.ORDERS.stream().peek(o -> System.out.println(" peek (never printed)")).count();
System.out.println("count = " + n);
long m = Data.ORDERS.stream().peek(o -> System.out.print("")).filter(o -> true).count();
System.out.println("with a filter it must look: " + m);
}
}Make the invisible visible: Run it.
-- no terminal operation:
(nothing ran)
-- add findFirst (short-circuiting terminal):
peek order 1
peek order 2
peek order 3
found order 3 after looking at 3 of 12
-- count() can skip the pipeline entirely (JDK 9+):
count = 12
with a filter it must look: 12What you see: The first pipeline printed nothing: "(nothing ran)". The findFirst pipeline printed order 1, 2 and 3 and stopped, since order 3 is the first cancelled one. The first count printed nothing and still returned 12, because the list's size is known. The second, with a filter, returned 12 as well, because it had to look.
Why: Laziness means the work follows the demand. No demand, no work. Short demand, short work.
No terminal
Looks busy, does nothing.
orders.stream()
.peek(o -> log.info("order {}", o.id()))
.map(Order::totalCents);
// log line never appearsWith terminal
Pulls, element by element.
orders.stream()
.peek(o -> log.info("order {}", o.id()))
.map(Order::totalCents)
.toList();
// 12 log lines, one per elementThe shift: The only difference is the last call, and it decides whether any of the code above it ever runs.
Land it With no terminal operation nothing runs, and with one the pipeline runs only as far as the terminal operation needs, which I can prove with a printing peek.
- "Why would someone write a pipeline without a terminal operation?"
-
By accident, almost always. A typical case: a developer wants to log each order, writes
orders.stream().map(this::audit);and believes it audits. The compiler does not complain, because an unused return value is legal. The audit never happens, and a test that only checks "no exception" passes.Another way is a refactor that moves a
forEachinto a helper and forgets one call. Code review tools and IDE inspections ("result of stream operation is not used") find it, so turn them on.The fix is to use the right terminal operation for what you want:
forEachfor effects,collectortoListfor results. For effects on a list, a plainforloop is often the clearest.When you debug a "nothing happens" report, check for a missing terminal operation before anything else. It is a two-second check.
- "What exactly does peek do, and should it be used?"
-
peek(consumer)is an intermediate operation that passes each element through unchanged and runs the consumer on it as a side effect. Its documented purpose is debugging: to see elements as they pass a stage.It has the same laziness as everything else. It runs only for elements that reach it, only when a terminal operation pulls, and the JDK documentation warns that the implementation may skip it when the result does not depend on the elements (the
count()case above).Use
peekto understand a pipeline while developing, as the demos do. Remove it before committing, or keep it behind a debug flag. For real side effects, useforEachat the end.A telling failure: someone used
peekto save to a database, and it stopped saving after a JDK upgrade madecount()skip the pipeline. - "Which terminal operations can skip the pipeline?"
-
Only those that can compute the answer from the source's size without looking at elements, and only in the stages above any filter.
count()is the known one. If the source is a sized collection, and all steps so far are one-to-one (map,peek,sorted), the count equals the source size. Addingfilter,flatMap,distinctorlimitbreaks that, because the output size is unknown.That optimisation came in Java 9. Before it,
count()always ran the pipeline, so code that relied on side effects frommaporpeekkept working until the upgrade.The lesson is general: the language guarantees the result of a pipeline, never the exact set of calls made to get it. Keep lambdas free of effects that matter, and the optimisation becomes harmless.
If a side effect must happen for every element, do it in
forEachor in a plain loop, not in a middle stage. - "How do I debug a stream pipeline?"
-
Three tools. First,
peekbetween stages, printing or logging what passes, as the demos do. Second, the IDE's stream debugger: IntelliJ has a "Trace Current Stream Chain" feature that shows each stage's input and output in a table, which is the closest thing to seeing the vertical order directly.Third, break the chain: assign an intermediate stage to a variable and put a breakpoint on a lambda body. A breakpoint inside a lambda works and shows one element at a time.
If the pipeline is too tangled to debug, that is a sign to simplify it: extract the lambdas into named methods, or return to a loop for that part.
Also check the order of operations. Most "wrong result" bugs are a
filterplaced after alimit, or asortedthat should come earlier or later.
Q35. "Are elements processed stage by stage or one element at a time? Show it."
Reveal answer
Strong answer One element at a time. A stream does not run all of filter over the whole list and then all of map. Each element travels through all stages before the next element starts. This is called vertical processing, as opposed to the horizontal (stage by stage) picture most people draw first.
The trace for filter then map over four items shows it: filter biryani, map biryani, filter raita, map raita, filter dosa (rejected, so no map), filter idli (rejected). The sequence interleaves the stages.
Why it matters. First, it avoids building intermediate lists, so a pipeline over a huge source uses little memory. Second, it makes short-circuiting possible: with limit(1) the pipeline stops after the first element has gone through, and the other three are never examined. Third, it explains surprising output order from peek and from side effects.
The exception is a stateful operation such as sorted, which must receive every element before it can pass any on (question 37). At that stage the stream does hold everything.
For parallel streams the elements of different chunks are processed at the same time, but inside one chunk it is still one element at a time through all stages.
Picture it A pipeline of two stages prints a line per call, next to what a stage-by-stage loop would have printed.
The setup: Q35_Vertical.java runs filter(length > 4) then map(toUpperCase) over four items, each stage printing its name and the item. It runs a second pipeline with limit(1) and then writes the stage-by-stage version as two plain loops for comparison.
import java.util.*;
import java.util.stream.*;
public class Q35_Vertical {
public static void main(String[] args) {
List<String> items = List.of("biryani", "raita", "dosa", "idli");
System.out.println("-- stream: element at a time");
List<String> out = items.stream()
.filter(s -> { System.out.println(" filter " + s); return s.length() > 4; })
.map(s -> { System.out.println(" map " + s); return s.toUpperCase(); })
.toList();
System.out.println(out);
System.out.println("-- with limit(1): the pipeline stops early");
items.stream()
.filter(s -> { System.out.println(" filter " + s); return s.length() > 4; })
.map(s -> { System.out.println(" map " + s); return s.toUpperCase(); })
.limit(1).toList();
System.out.println("-- what a stage-by-stage model would print:");
var stage1 = new ArrayList<String>();
for (String s : items) { System.out.println(" filter " + s); if (s.length() > 4) stage1.add(s); }
for (String s : stage1) System.out.println(" map " + s);
}
}Make the invisible visible: Run it.
-- stream: element at a time
filter biryani
map biryani
filter raita
map raita
filter dosa
filter idli
[BIRYANI, RAITA]
-- with limit(1): the pipeline stops early
filter biryani
map biryani
-- what a stage-by-stage model would print:
filter biryani
filter raita
filter dosa
filter idli
map biryani
map raitaWhat you see: The stream trace interleaves the stages: filter biryani, map biryani, filter raita, map raita, then filter dosa and filter idli with no map. With limit(1) only "filter biryani" and "map biryani" ran. The loop version, by contrast, printed all four filters before any map.
Why: Each stage hands the element to the next stage immediately. The stage-by-stage version would have to store a whole list between the stages.
Stage by stage
What most people picture.
filter biryani
filter raita
filter dosa
filter idli
map biryani
map raitaOne at a time
What a stream does.
filter biryani
map biryani
filter raita
map raita
filter dosa
filter idliThe shift: The output shows the order of calls: each element goes all the way through before the next one starts.
Land it A stream sends each element through every stage before the next element starts, which is why it needs no intermediate lists and can stop early.
- "Does this change if I use sorted?"
-
Yes.
sortedis a barrier. It cannot output the smallest element until it has seen all the elements, so it collects everything first, sorts, and only then passes elements on one at a time. Before the barrier the processing is vertical. After it, vertical again. In the middle, the whole data set sits in memory.So
peek(A).sorted().peek(B)prints all of the A lines first, then the B lines, as the trace in question 37 shows.That has two practical effects. The pipeline cannot short-circuit across a
sorted: evenlimit(1)after it needs to sort everything. And on a huge or infinite source it will run out of memory.To keep the benefits of laziness, put
filterbeforesortedso fewer elements reach the barrier, and remember thatsorted().limit(10)still sorts the whole input first (question 37 measures it). - "Why is the order of filter and map important for performance?"
-
Because each element goes through every stage, and a cheap early
filtermeans expensive later stages never run for discarded elements.filter(cheap).map(expensive)pays the expensive cost only for survivors.map(expensive).filter(cheap)pays it for everyone.The same holds for
limit.filter(...).limit(10)stops after the tenth match.limit(10).filter(...)takes ten elements first and then filters, giving you fewer than ten results. They answer different questions, and mixing them up is a frequent bug.A good habit: put the stage that removes the most elements, and is cheapest to evaluate, as early as possible. Then put
sortedanddistinct, which need memory, after it.Measure if it matters. For small collections, the order has no visible effect, and clarity should decide.
- "Is this also true for parallel streams?"
-
Within one chunk, yes. The source is split into parts (question 55), and each worker processes its part element by element through all stages. Across parts, different elements are in different stages at the same moment, so the printed trace of a parallel pipeline is interleaved and different on each run.
That is why side effects in a parallel pipeline are dangerous. The order is not just "vertical", it is also not repeatable. A
forEachthat prints produces a different order every time, which is what theforEachOrderedvariant exists to control (question 59).The results of operations that have a defined order, such as
toList()andcollect(toList()), are still delivered in the source order, because the framework combines the parts in order.The rule: the result of a parallel pipeline is as defined as a sequential one if your lambdas are pure, but the trace is not.
- "How do I print the trace of a real pipeline without changing it much?"
-
Add
peekat the points you care about, with a label:.peek(o -> System.out.println("after filter " + o.id())). Remove them afterwards. The demos in this chapter do exactly that.For a quick look at what a stage produces without the interleaving, collect into a list at that point with
toList()and print it, in a scratch copy of the pipeline.In IntelliJ, "Trace Current Stream Chain" on a breakpoint draws the pipeline as a table for you.
If your tracing changes the result (for example you added a
sortedto read the output more easily), remember that you changed the pipeline. Add it only to the scratch copy.
Q36. "Which operations short-circuit, and why does limit work on an infinite stream?"
Reveal answer
Strong answer A short-circuiting operation can finish without looking at every element. There are two groups. Intermediate: limit(n), takeWhile(p) (Java 9). Terminal: findFirst, findAny, anyMatch, allMatch, noneMatch. The Javadoc marks them as "short-circuiting".
limit(5) works on an infinite stream because of laziness and one-at-a-time processing. The terminal operation asks for an element; the element travels up the chain from the source; limit counts it. After the fifth one, limit answers "no more" to the next request, and the pipeline stops asking the source. The infinite source is never asked for its sixth element.
Likewise anyMatch stops at the first true, allMatch stops at the first false and noneMatch stops at the first true. They are the stream versions of || and &&.
Two cautions. A stateful step before the short-circuit defeats it: Stream.iterate(1, i -> i + 1).sorted().limit(5) never finishes, because sorted waits for an end that never comes (question 37 runs it). And an infinite stream needs some short-circuit terminal or limit. A plain collect on it runs until memory is gone.
For finite sources the benefit is speed: findFirst on a million orders may look at three.
Picture it Counting how many elements each short-circuit actually pulled from an infinite source and from the twelve orders.
The setup: Q36_ShortCircuit.java counts pulls with a peek and an AtomicInteger. It runs iterate with filter and limit, anyMatch, allMatch and findFirst, then shows Java 9's three-argument iterate and takeWhile.
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.*;
public class Q36_ShortCircuit {
public static void main(String[] args) {
var pulled = new AtomicInteger();
// an infinite source: 1, 2, 3, ... forever
List<Integer> firstFiveEvens = Stream.iterate(1, i -> i + 1)
.peek(i -> pulled.incrementAndGet())
.filter(i -> i % 2 == 0).limit(5).toList();
System.out.println(firstFiveEvens + " pulled " + pulled + " numbers from the infinite source");
pulled.set(0);
boolean any = Stream.iterate(1, i -> i + 1).peek(i -> pulled.incrementAndGet()).anyMatch(i -> i * i > 200);
System.out.println("anyMatch(i*i > 200) = " + any + ", pulled " + pulled);
pulled.set(0);
boolean all = Stream.iterate(1, i -> i + 1).peek(i -> pulled.incrementAndGet()).allMatch(i -> i < 10);
System.out.println("allMatch(i < 10) = " + all + ", pulled " + pulled + " (a false answer is found early)");
pulled.set(0);
var o = Data.ORDERS.stream().peek(x -> pulled.incrementAndGet()).filter(x -> x.city().equals("Mysuru")).findFirst();
System.out.println("findFirst Mysuru -> order " + o.get().id() + ", looked at " + pulled + " of 12");
System.out.println("Java 9 three-argument iterate: " + Stream.iterate(1, i -> i <= 100, i -> i * 3).toList());
System.out.println("takeWhile: " + Stream.iterate(1, i -> i + 1).takeWhile(i -> i < 6).toList());
}
}Make the invisible visible: Run it.
[2, 4, 6, 8, 10] pulled 10 numbers from the infinite source
anyMatch(i*i > 200) = true, pulled 15
allMatch(i < 10) = false, pulled 10 (a false answer is found early)
findFirst Mysuru -> order 3, looked at 3 of 12
Java 9 three-argument iterate: [1, 3, 9, 27, 81]
takeWhile: [1, 2, 3, 4, 5]What you see: The first five even numbers needed only 10 pulls from the infinite source. anyMatch(i*i > 200) stopped at 15, since 15 squared is 225. allMatch(i < 10) found a counter-example at the tenth element and stopped. findFirst for Mysuru looked at 3 of the 12 orders. The three-argument iterate produced [1, 3, 9, 27, 81] and stopped when the condition failed.
Why: Short-circuiting is an agreement between the stages: when the last one says "enough", nothing upstream is asked again.
Loop
Break out by hand.
int n = 0;
for (int i = 1; ; i++) {
if (i % 2 == 0) { out.add(i); n++; }
if (n == 5) break;
}Stream
The limit stops the source.
var out = Stream.iterate(1, i -> i + 1)
.filter(i -> i % 2 == 0)
.limit(5)
.toList();The shift: The stop condition is part of the pipeline, so there is no counter and no break to get wrong.
Land it The short-circuiting operations are limit, takeWhile, findFirst, findAny, anyMatch, allMatch and noneMatch, and limit works on infinite streams because the source is only asked for what is demanded.
- "What is the difference between limit and takeWhile?"
-
limit(n)stops after a fixed count.takeWhile(predicate)stops at the first element that fails a condition. Uselimitwhen you know how many you want, andtakeWhilewhen you know when to stop.takeWhileassumes the stream is ordered the way you expect: it stops at the first failure and ignores the rest, even if later elements would pass. On unsorted data it can return less thanfilterwould, as question 44 shows.For infinite streams both work:
Stream.iterate(1, i -> i * 2).takeWhile(i -> i < 100)gives the powers of two below 100.Before Java 9 there was no
takeWhile, so people wrote a loop or a custom iterator, or used the three-argumentStream.iterate(seed, hasNext, next), which has the stop condition built in. - "Why does filter then limit give different results from limit then filter?"
-
Because stages run in the order you write them.
filter(even).limit(5)keeps looking until it has found five even numbers, so you get five.limit(5).filter(even)takes the first five numbers (1 to 5) and then filters, giving you only 2 and 4.The same difference appears with
sorted:sorted().limit(3)gives the three smallest, whilelimit(3).sorted()sorts the first three that happened to arrive.That is not a bug. It is the vertical pipeline doing what it is told. But it is a common bug in code, because the two orders read almost the same. Say it aloud: "take five, then keep the even ones", against "keep the even ones, then take five".
When I review stream code, I check
limitandskippositions first, since a wrong place there gives a plausible but wrong answer. - "What happens with findFirst on an unordered or parallel stream?"
-
findFirstreturns the first element in the stream's encounter order, which for a list is list order. In a parallel stream it must still return the first one in that order, so parallel workers may do extra work and then discard it: a worker that finds a match in a later chunk must wait to see whether an earlier chunk has a match.findAnyis allowed to return any element, so a parallel stream can return the first one any worker finds. It is faster in parallel for that reason. If you do not care which match you get, such as "is there any delivered order", usefindAnyoranyMatch.On a sequential stream the two behave the same in practice. The difference is the contract: write
findAnywhen any is fine, so readers and the library know that the order does not matter.Question 59 measures the ordering cost.
- "Can I short-circuit a forEach, or exit a stream early like a break?"
-
Not with
forEach. It has no way to stop, and throwing an exception to escape is an abuse that makes code hard to follow. The stream-friendly options are to restructure the pipeline so that a short-circuit operation ends it:takeWhilebefore theforEach,limitbefore it, oranyMatchwith a predicate that performs the action and returns whether to stop.The last one is a known trick, and a questionable one: using a predicate with side effects is exactly what to avoid. If the loop has a real early exit with several statements, a plain
forwithbreakorreturnis clearer (question 45).A Java 24 gatherer can also stop a stream: its integrator returns
falseto say "stop" (question 18), which is a clean way to write a custom stop rule.My choice:
takeWhileorlimitfor simple rules, a loop for complex ones.
Q37. "Stateless versus stateful operations (sorted, distinct): why do stateful ones matter?"
Reveal answer
Strong answer A stateless operation handles each element on its own, with no memory of the others: filter, map, flatMap, peek, mapToInt. It can run on any element at any time, which is why it parallelises easily and streams element by element.
A stateful operation needs information from other elements. sorted needs every element before it can say which is smallest. distinct remembers what it has seen. limit and skip count elements. sorted is the heavy one: it is a barrier that holds the whole input in memory until the input ends.
Why it matters: memory, because a barrier stores everything (an infinite stream with sorted fills the heap); laziness, since the pipeline cannot short-circuit across a barrier; and parallel speed, since stateful operations need coordination between threads or a combine step, so they limit speed-ups.
Practical advice: put filter before stateful steps so fewer elements reach them; for a top-n over huge data do not trust sorted().limit(n), which sorts everything first (shown below), and use a bounded heap; avoid distinct and sorted on parallel streams of huge data unless you measured; and note that distinct on an ordered parallel stream is more expensive than on an unordered one.
Also: lambdas that use external mutable state (a counter, a list) are stateful lambdas, which is different and bad (question 42).
Picture it A trace shows a stateless chain passing elements through one by one, then a sorted barrier holding everything back, then distinct remembering, then the heap running out.
The setup: Q37_Stateful.java prints a line when an element enters and leaves each stage. The last part runs sorted().limit(5) on an infinite stream with the heap capped at 32 MB (java -Xmx32m).
import java.util.*;
import java.util.stream.*;
public class Q37_Stateful {
public static void main(String[] args) {
System.out.println("-- stateless filter + map: one element all the way down");
Stream.of("dosa", "biryani", "idli").filter(s -> true).map(s -> { System.out.println(" map " + s); return s; })
.forEach(s -> System.out.println(" got " + s));
System.out.println("-- sorted in the middle: everything must arrive before anything leaves");
Stream.of("dosa", "biryani", "idli")
.peek(s -> System.out.println(" before sorted: " + s))
.sorted()
.peek(s -> System.out.println(" after sorted: " + s))
.findFirst();
System.out.println("-- distinct remembers what it has seen");
Stream.of(1, 2, 1, 3, 2).peek(i -> System.out.print(" in " + i)).distinct().forEach(i -> System.out.println(" -> out " + i));
System.out.println("-- limit AFTER sorted on an infinite stream, heap capped at 32 MB:");
try {
Stream.iterate(1, i -> i + 1).sorted().limit(5).forEach(System.out::println);
} catch (OutOfMemoryError e) { System.out.println(" " + e); }
}
}Make the invisible visible: Run it with the small heap.
-- stateless filter + map: one element all the way down
map dosa
got dosa
map biryani
got biryani
map idli
got idli
-- sorted in the middle: everything must arrive before anything leaves
before sorted: dosa
before sorted: biryani
before sorted: idli
after sorted: biryani
-- distinct remembers what it has seen
in 1 -> out 1
in 2 -> out 2
in 1 in 3 -> out 3
in 2-- limit AFTER sorted on an infinite stream, heap capped at 32 MB:
java.lang.OutOfMemoryError: Java heap spaceWhat you see: The stateless chain handled each element all the way down before taking the next. With sorted in the middle, all three "before sorted" lines appeared first, and only then "after sorted: biryani" (the smallest in alphabetical order). distinct printed out only the first time each value arrived. And the infinite sorted ended in java.lang.OutOfMemoryError: Java heap space without ever printing a value.
Why: sorted cannot start emitting until the stream ends, and an infinite stream never ends. That is the price of a barrier.
Stateless
One element in, one decision.
orders.stream()
.filter(o -> o.totalCents() > 30000)
.map(Order::id);
// no memory between elementsStateful
Needs the others.
orders.stream()
.map(Order::totalCents)
.sorted() // holds all 12
.distinct(); // remembers seenThe shift: A stateful step stores data from other elements, so it costs memory and prevents the pipeline from running element by element.
Land it Stateless operations treat each element alone, while stateful ones like sorted and distinct remember other elements, which costs memory, blocks short-circuiting and limits parallel speed.
- "Is sorted().limit(10) efficient, or does it sort everything?"
-
It sorts everything. It is natural to expect the library to notice that only ten results are wanted and keep a small heap, but the stream does not do that.
sorted()is a barrier that collects all elements into an array and sorts the whole array beforelimitsees the first one.The measurement below uses 5,000,000 random numbers and a heap capped at 48 MB. The stream version runs out of memory. A hand-written bounded heap, which holds only ten numbers at any moment, finishes with the same data and keeps nearly no memory.
Q37_TopN.java · Java 25 (java -Xmx48m)runs offlineimport java.util.*; import java.util.stream.*; public class Q37_TopN { public static void main(String[] args) { try { List<Integer> top = new Random(42).ints(5_000_000, 0, 1_000_000).boxed().sorted().limit(10).toList(); System.out.println("sorted().limit(10) worked: " + top); } catch (OutOfMemoryError e) { System.out.println("sorted().limit(10) -> " + e); } PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder()); // keeps the 10 smallest new Random(42).ints(5_000_000, 0, 1_000_000).forEach(i -> { heap.add(i); if (heap.size() > 10) heap.poll(); }); List<Integer> smallest = new ArrayList<>(heap); Collections.sort(smallest); System.out.println("bounded heap, same data, 10 elements in memory: " + smallest); } }output · measured on the course machineruns offlinesorted().limit(10) -> java.lang.OutOfMemoryError: Java heap space bounded heap, same data, 10 elements in memory: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]So for a small list,
sorted().limit(n)is fine and readable. For millions of elements, or an unbounded source, use aPriorityQueuekept at size n, as a custom collector (question 53 builds one).The practical rule: the cost of
sortedis the size of the input, whatever comes after it. - "Why is distinct slow in parallel streams?"
-
On an ordered stream,
distinctmust keep the first occurrence of each value in encounter order. In parallel, one worker may see a duplicate before another worker has seen the earlier original, so the library has to track encounter positions and coordinate between chunks. That costs memory and synchronisation.If you do not care which duplicate survives, call
unordered()first.distinctcan then run with a concurrent set, which is faster, and may keep any occurrence.For sequential streams,
distinctis just aHashSetand fast.The rule I follow: for large data, measure parallel
distinctagainst sequential. Often the sequential version wins unless the data is large and per-element work is heavy. - "Can a stateful operation return wrong results in parallel?"
-
The built-in ones are written to give the same result as sequential for ordered streams, at the cost of speed. The danger is stateful lambdas that you write: a
mapwhose function reads and changes a counter, or afilterthat adds to a set. Those break in parallel because several threads change the same variable.The JDK documentation calls these lambdas non-interfering and stateless as requirements: do not change the source while streaming, and do not depend on state that changes during the pipeline. Violating the rules gives unpredictable results, not a clean exception.
For example, a
mapthat numbers the elements with anAtomicIntegerworks in sequential order but numbers the elements in a different order on every parallel run.If you need positions, use
IntStream.rangeand index into the list, or a gatherer such asscan(question 54). - "What other operations are stateful?"
-
Besides
sortedanddistinct:limit,skipand, in a loose sense,takeWhileanddropWhile(they remember whether the condition has failed).limitandskipare cheap to run sequentially and expensive in ordered parallel streams, because a worker must know how many elements came before its chunk.The gatherers added in Java 24 can be stateful by design:
windowFixed,windowSliding,scan. They remember the current window or the running total, and the library runs them sequentially when order matters.The terminal operations are separate:
reduceandcollectkeep state, but they do it in a controlled way (an accumulator per chunk, then combine), which is why they are safe in parallel while your own shared variable is not.So the list to remember is: sorted, distinct, limit and skip.
Q38 · Scenario. "“stream has already been operated upon or closed” — what happened and how do you fix it?"
Reveal answer
Strong answer A stream was used twice. A stream is a single-use pipeline: after one terminal operation (such as count or collect), it is marked used up. Calling any other operation on that same stream object throws this:
IllegalStateException: stream has already been operated upon or closedThe same message appears when you attach two operations to one intermediate stage (branching), because an intermediate operation also marks its input as used.
The typical cause is storing a stream in a field or variable "to reuse it": Stream<Order> delivered = orders.stream().filter(...) in a static field, called twice. The first call works. The second fails, and it fails far from the line that created the stream, which makes the report confusing.
Fixes, in order of preference. Store the result, not the stream: List<Order> delivered = ...toList(), and stream from the list each time. If the data is large or must stay lazy, store a recipe:
Supplier<Stream<Order>> delivered =
() -> orders.stream().filter(...)and call get() for each use. And if you need several answers from one pass, compute them together with teeing or summarizingInt.
Never "fix" it by catching the exception. The exception is the design telling you the stream is spent.
Picture it The error reproduced with a stored stream, and the two fixes side by side.
The setup: Q38_Reuse.java keeps a stream in a static field and calls count() twice. It then fixes the problem with a Supplier and with a List, and finally shows the branching form of the error.
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.*;
public class Q38_Reuse {
static Stream<Order> delivered = Data.ORDERS.stream().filter(o -> o.status().equals("DELIVERED")); // BUG: stored stream
public static void main(String[] args) {
System.out.println("first use : " + delivered.count());
try { System.out.println("second use: " + delivered.count()); }
catch (IllegalStateException e) { System.out.println("second use: " + e); }
// Fix 1: store the recipe, not the stream
Supplier<Stream<Order>> deliveredRecipe = () -> Data.ORDERS.stream().filter(o -> o.status().equals("DELIVERED"));
System.out.println("fix 1: " + deliveredRecipe.get().count() + " then " + deliveredRecipe.get().mapToInt(Order::totalCents).sum());
// Fix 2: store the result, a List
List<Order> list = Data.ORDERS.stream().filter(o -> o.status().equals("DELIVERED")).toList();
System.out.println("fix 2: " + list.size() + " then " + list.stream().mapToInt(Order::totalCents).max().getAsInt());
// the same error inside one method: chaining on a variable that was already consumed
Stream<String> names = Data.ORDERS.stream().map(Order::customer);
Stream<String> upper = names.map(String::toUpperCase);
try { names.map(String::length); } catch (IllegalStateException e) { System.out.println("branching: " + e.getMessage()); }
System.out.println(upper.distinct().count());
}
}Make the invisible visible: Run it.
first use : 8
second use: java.lang.IllegalStateException: stream has already been operated upon or closed
fix 1: 8 then 324400
fix 2: 8 then 89400
branching: stream has already been operated upon or closed
4What you see: The first count() returned 8 (the delivered orders). The second threw this:
IllegalStateException: stream has already been operated upon or closedFix 1 (the supplier) gave 8 and then the revenue 324,400. Fix 2 (the list) gave 8 and the maximum 89,400. The branching case threw the same message: names had been used to create upper, so a second use of names was refused.
Why: The stream keeps a flag "already linked or consumed". The second use finds the flag set and refuses, which protects you from reading a half-consumed source.
Stored stream
Works once.
static Stream<Order> delivered =
orders.stream().filter(isDelivered);
delivered.count(); // ok
delivered.count(); // IllegalStateExceptionStored recipe
Fresh stream each time.
static Supplier<Stream<Order>> delivered =
() -> orders.stream().filter(isDelivered);
delivered.get().count(); // ok
delivered.get().count(); // okThe shift: A Supplier hands out a new stream on demand, so each use starts from a fresh pipeline.
Land it A stream is single-use, so I store a List or a Supplier of Streams instead of a stream, and compute several answers in one pass with teeing when that fits.
- "Why not make streams reusable?"
-
A stream may sit on a one-time source: a network connection, a file, a database cursor or a generator that cannot be rewound. Reusing it would mean reading the source twice, which is impossible for some sources and expensive for others. The designers chose a rule that is always true: one pass.
It also keeps the implementation simple and fast. The stream does not need to remember elements to replay them.
The cost is the occasional exception, which is a clear signal. If you need replay, the answer is a collection: it stores elements, can be streamed any number of times, and says so in its type.
In other languages, iterators and generators have the same one-pass property. A
Streamis closer to anIteratorthan to aList. - "When is a Supplier better than a List?"
-
When the data is large and you do not want it all in memory, or when the stream does expensive per-element work that you want to run again with fresh data (for example reading a file each time). A
Listis simpler and faster for repeated use when the data fits in memory, since the work is done once.A supplier recomputes the whole pipeline on each
get(), so the cost is paid every time. Be sure that is what you intend. A pipeline that calls a service for each element will call it again.A rule of thumb: if the pipeline is cheap, or the data changes between uses and you want the new data, use a supplier. If the pipeline is expensive and the data is fixed, store the list.
In both cases name the thing for what it is:
deliveredOrders()returning a fresh stream, ordeliveredListholding results, so that no one expects the wrong behaviour. - "How does this error appear with Files.lines or database streams?"
-
Files.lines(path)and Spring Data's stream-returning repository methods give streams that hold an open resource. They must be closed, and they fail in the same way if used twice. If a method returns such a stream and the caller already closed the surrounding transaction or file, the error is different: the stream reads from a closed source and fails with an I/O or database exception.The safe pattern is try-with-resources:
try (Stream<String> lines = Files.lines(path)) { ... }, and produce the result inside the block. Never return the stream from a method that closes its resource.With streams from a database, consume them inside the same transaction. Returning a stream from a
@Transactionalmethod to a caller outside it fails, because the transaction has ended.The fix there is to return a list, or to pass the processing in as a lambda so that the resource's owner controls the lifetime.
- "Does the error ever happen without me reusing a variable?"
-
Yes, in a few indirect ways. A method that returns a cached stream hands the same object to every caller. A lambda that uses a stream from the enclosing scope (
list.forEach(x -> stream.filter(...))) calls it again for each element, so the second element triggers the error. And a field that holds a stream, initialised once in a constructor, fails on the second call to any method that uses it.The common thread is a stream whose lifetime is longer than one pipeline. The stack trace points at the second use, which is a symptom. The cause is the earlier line that stored or shared the stream.
So search for fields and static variables of type
Stream, and for methods that return a stream they did not just create. Those are the places the bug lives.An IDE inspection warns about a stream stored in a field. Turn it on.
Q39. "map versus flatMap versus mapMulti (16)."
Reveal answer
Strong answer All three transform each element. They differ in how many outputs one input can produce.
map: one in, one out. orders.stream().map(Order::lines) gives a Stream<List<Line>>: one list per order, still nested.
flatMap: one in, a stream out (zero, one or many elements), and the library joins all those streams into one. orders.stream().flatMap(o -> o.lines().stream()) gives a flat Stream<Line>. Returning an empty stream drops the element, so flatMap can also filter. It is the standard tool for "list of lists", for splitting text into words, and for unpacking Optional values (flatMap(Optional::stream)).
mapMulti (Java 16): one in, and you push zero or more outputs into a sink:
mapMulti((order, sink) -> {
for (Line l : order.lines()) sink.accept(l);
})It does the same job as flatMap but without creating a temporary stream object for each element, so it is cheaper when most inputs produce zero or one output, or only a few. The cost is that the lambda is a bit lower level and often needs a type witness: .<String>mapMulti(...).
A fourth, related one: mapToInt, mapToLong and mapToObj change between primitive and object streams.
Choose: map for one-to-one, flatMap as the default for one-to-many, and mapMulti when profiling shows many small temporary streams.
Picture it Orders go through all three on QuickBite data, with the nested result of a plain map shown for contrast.
The setup: Q39_FlatMap.java uses the first three orders. It prints how many lines each order has with map, shows that the result is still nested, flattens with flatMap, uses flatMap to drop a bad number, uses mapMulti to keep only lines with quantity of two or more, and flattens a list of Optional.
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.*;
public class Q39_FlatMap {
public static void main(String[] args) {
List<Order> few = Data.ORDERS.subList(0, 3);
// map: one in, one out -> a Stream of Lists
System.out.println(few.stream().map(Order::lines).map(List::size).toList() + " <- lines per order");
System.out.println(few.stream().map(Order::lines).toList().get(0).size() + " <- still nested: List<List<Line>>");
// flatMap: one in, a Stream out (zero, one or many), results flattened
System.out.println(few.stream().flatMap(o -> o.lines().stream()).map(Line::item).toList());
// flatMap with zero: drops the element
System.out.println(Stream.of("1", "x", "3").flatMap(s -> { try { return Stream.of(Integer.parseInt(s)); }
catch (NumberFormatException e) { return Stream.empty(); } }).toList());
// mapMulti (16): same idea, but pushes into a sink, no temporary Stream per element
List<String> items = few.stream().<String>mapMulti((o, sink) -> {
for (Line l : o.lines()) if (l.qty() >= 2) sink.accept(o.id() + ":" + l.item());
}).toList();
System.out.println(items);
// optionals into a stream
System.out.println(Stream.of(Optional.of(1), Optional.<Integer>empty(), Optional.of(3)).flatMap(Optional::stream).toList());
System.out.println(Stream.of("a b", "c").flatMap(s -> Arrays.stream(s.split(" "))).toList());
}
}Make the invisible visible: Run it.
[2, 1, 1] <- lines per order
2 <- still nested: List<List<Line>>
[biryani, raita, masala dosa, paneer tikka]
[1, 3]
[1:biryani, 2:masala dosa]
[1, 3]
[a, b, c]What you see: map gave [2, 1, 1] lines per order, and the element it produced for order 1 was still a list of 2, so the stream is nested. flatMap gave the four item names in one flat list. An empty stream for the invalid "x" removed it, leaving [1, 3]. mapMulti kept the two lines with quantity 2 or more (biryani, masala dosa). The Optionals flattened to [1, 3].
Why: flatMap answers "give me many things for this one thing" and joins them. A plain map only changes one thing into another thing.
map
Nested: a stream of lists.
Stream<List<Line>> s =
orders.stream()
.map(Order::lines);
// [[biryani, raita], [dosa], ...]flatMap
Flat: a stream of lines.
Stream<Line> s =
orders.stream()
.flatMap(o -> o.lines().stream());
// [biryani, raita, dosa, ...]The shift: flatMap opens each inner list and puts its elements straight into the outer stream.
Land it map changes one into one, flatMap changes one into many and flattens, and mapMulti does the same with a sink when the temporary streams cost too much.
- "When is mapMulti really better than flatMap?"
-
When most inputs yield zero or one output, or when you already have the results in a loop.
flatMapmust create aStreamobject for every element, even an empty one, and then merge them. For millions of elements with small outputs, that allocation shows up in a profile.mapMultiskips it: it hands you a sink and you callaccept.It also lets you write the logic as a plain loop with conditions and early exit, which can be clearer than building a stream inside a lambda. The Javadoc recommends it where "replacing each stream element with a small (possibly zero) number of elements".
For ordinary code,
flatMapis shorter and well known, so choose it first. UsemapMultiafter a measurement or when the logic is already a loop.The type witness (
.<String>mapMulti) is needed because the compiler cannot infer the output type from a lambda that only calls the sink. - "How do I turn a list of lists, or a map of lists, into a flat stream?"
-
For a list of lists:
lists.stream().flatMap(List::stream). For a map whose values are lists:map.values().stream().flatMap(List::stream), or this form if you need the key with each value:flatMap over map entriesruns offlinemap.entrySet().stream() .flatMap(e -> e.getValue().stream().map(v -> Map.entry(e.getKey(), v)))Two-level data such as orders with lines is the typical case:
orders.stream().flatMap(o -> o.lines().stream())gives every line across all orders. If you need the parent too, build a pair inside theflatMap(a record such asOrderLine(Order order, Line line)or aMap.entry), as the top-three question does (question 50).For primitives there are
flatMapToInt,flatMapToLongandflatMapToDouble.If a nested value may be null, guard it inside:
o.lines() == null ? Stream.empty() : o.lines().stream(). - "What is the difference between flatMap on Stream and on Optional?"
-
The idea is the same: a function that returns a container, flattened so you do not get a container of containers. On a
Stream, the function returns a stream and the results are concatenated. On anOptional, the function returns an Optional and the result is that Optional itself (or empty).They connect through
Optional.stream()(Java 9), which turns an Optional into a stream of zero or one element. That makes the clean way to drop empties from a stream of Optionals:flatMap(Optional::stream), as the demo does. Before Java 9 the idiom wasfilter(Optional::isPresent).map(Optional::get), which is longer and uses the uncheckedget.Think of
flatMapas "map, then remove one layer of wrapping". Where a wrapper (stream, optional, future) holds another wrapper of the same kind, flatMap is the tool.CompletableFuture.thenComposeis the same idea for async results.When you see an unwanted
Stream<Stream<T>>orOptional<Optional<T>>in a type error, replacemapwithflatMap. - "Does flatMap process lazily, or does it build the inner streams up front?"
-
It is lazy: each inner stream is created when its element is reached, and its elements are passed on one at a time. Since Java 10 it is also properly short-circuiting:
flatMap(...).findFirst()stops inside the first inner stream that produces an element. In Java 8 and 9 a bug meant the whole inner stream was consumed even when only one element was needed. This was fixed in Java 10.This matters when the inner stream is expensive or infinite.
flatMap(x -> Stream.iterate(...))followed bylimitdoes not finish on Java 8, and works on later versions.If you have to support an old JDK and rely on laziness inside
flatMap, test it.One more cost to know: each inner stream is closed after use, so an inner stream that holds a resource (like
Files.lines) is released properly byflatMap.
Q40. "reduce versus collect — when is reduce the wrong tool?"
Reveal answer
Strong answer reduce combines elements into one value of the same kind using an operation that creates a new value each time: reduce(0, Integer::sum), reduce(Integer::max). The contract: the operation must be associative (grouping does not change the result) and must not change its inputs, because a parallel stream will combine partial results in any grouping.
collect is for mutable accumulation: building a list, a map, a string. It takes a supplier (create an empty container), an accumulator (add one element into it) and a combiner (merge two containers). Each thread gets its own container, and containers are merged at the end. That is why collect is safe in parallel and the mutable version of reduce is not.
Wrong tool, case 1:
reduce(new ArrayList<>(), (list, x) -> { list.add(x); return list; }, ...)The identity (one shared list) is used by every thread, so in parallel they all write into the same ArrayList. The demo shows it failing every time.
Wrong tool, case 2: building a string with reduce("", (a, b) -> a + b). It works but copies the growing string at every step, which is quadratic. Collectors.joining() uses a StringBuilder.
Wrong tool, case 3: a non-associative operation such as subtraction or "average of two": the result depends on grouping and changes in parallel.
Use reduce for sums, products, max, min and combining immutable values. Use collect for everything that builds a container.
Picture it reduce doing its proper job, then the mutable misuse run five times in parallel, the correct collect and the string concatenation timing.
The setup: Q40_ReduceCollect.java sums and takes the maximum of the order totals with reduce. It then runs a parallel reduce whose identity is one shared ArrayList five times, runs the same job with collect, and times string concatenation by reduce against joining for 20,000 numbers.
import java.util.*;
import java.util.stream.*;
public class Q40_ReduceCollect {
public static void main(String[] args) {
// reduce is right for combining values into one value of the same kind
int sum = Data.ORDERS.stream().map(Order::totalCents).reduce(0, Integer::sum);
Optional<Integer> max = Data.ORDERS.stream().map(Order::totalCents).reduce(Integer::max);
System.out.println("sum " + sum + " max " + max.get());
// reduce is the WRONG tool when the accumulator is mutable: all threads share one ArrayList
for (int run = 1; run <= 5; run++) {
try {
List<Integer> r = IntStream.range(0, 10_000).boxed().parallel().reduce(
new ArrayList<Integer>(),
(list, n) -> { list.add(n); return list; },
(a, b) -> { a.addAll(b); return a; });
System.out.println("run " + run + ": reduce -> " + r.size() + " elements (expected 10000)");
} catch (RuntimeException e) { System.out.println("run " + run + ": reduce -> " + e); }
}
List<Integer> ok = IntStream.range(0, 10_000).boxed().parallel().collect(
ArrayList::new, ArrayList::add, ArrayList::addAll); // collect: one container per thread, then merged
System.out.println("collect -> " + ok.size() + " elements");
// reduce on Strings copies the whole string at every step
long t0 = System.nanoTime();
String slow = IntStream.range(0, 20_000).mapToObj(Integer::toString).reduce("", (a, b) -> a + b);
long t1 = System.nanoTime();
String fast = IntStream.range(0, 20_000).mapToObj(Integer::toString).collect(Collectors.joining());
long t2 = System.nanoTime();
System.out.println("reduce concat " + (t1 - t0) / 1_000_000 + " ms, joining " + (t2 - t1) / 1_000_000 + " ms, same? " + slow.equals(fast));
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}Make the invisible visible: Run it.
sum 529700 max 89400
run 1: reduce -> java.lang.ArrayIndexOutOfBoundsException
run 2: reduce -> java.lang.ArrayIndexOutOfBoundsException
run 3: reduce -> java.lang.ArrayIndexOutOfBoundsException
run 4: reduce -> java.lang.ArrayIndexOutOfBoundsException
run 5: reduce -> java.lang.ArrayIndexOutOfBoundsException
collect -> 10000 elements
reduce concat 778 ms, joining 4 ms, same? true
// measured on the course machine (12 cores); your numbers will differWhat you see: The proper reduce calls gave the sum 529,700 and the maximum 89,400. The misused reduce failed in all five runs, with ArrayIndexOutOfBoundsException: several threads grew one ArrayList at once. The collect version returned all 10,000 elements. The string build took 778 ms by reduce and 4 ms by joining.
Why: reduce assumes it is combining values, not editing one shared object. collect gives each thread a private container, which is why it survives parallel execution.
reduce (wrong)
One shared list for all threads.
List<Integer> r = nums.parallelStream()
.reduce(new ArrayList<>(),
(l, n) -> { l.add(n); return l; },
(a, b) -> { a.addAll(b); return a; });collect
A private list per thread.
List<Integer> r = nums.parallelStream()
.collect(ArrayList::new,
ArrayList::add,
ArrayList::addAll);The shift: collect creates a fresh container for every chunk and merges them, so no two threads touch the same list.
Land it reduce is for combining values with an associative operation, and anything that builds a container or a string belongs in collect.
- "What does associative mean here, and how do I check it?"
-
An operation is associative if grouping does not matter:
(a + b) + cequalsa + (b + c). Addition, multiplication,maxandminare. Subtraction, division and "average of two numbers" are not. A parallel stream splits the data, reduces each part and combines the partial results, so it uses a grouping you did not choose. Only an associative operation gives the same result for every grouping.The identity must also be a true identity:
combine(identity, x)must equalx. Zero is the identity for addition and one for multiplication. Usingreduce(10, Integer::sum)adds 10 once per part in parallel, so the answer differs by the number of parts. That is a bug I have seen.A quick test: run the same reduce on a shuffled copy of the input and on a parallel stream. If the result changes, the operation is not associative.
Question 56 shows a subtraction
reducegiving different answers in sequential and parallel. - "What are the three arguments of the three-argument reduce, and when do I use them?"
-
They are
reduce(identity, accumulator, combiner). The accumulator folds one element into a partial result of a different type:(sum, order) -> sum + order.totalCents()turns anIntegersum and anOrderinto a new sum. The combiner merges two partial results:Integer::sum. It is used only when the stream is parallel, but you must provide it and it must be consistent with the accumulator.This form lets
reducechange type, fromOrdertointfor example. A simpler way is usuallymapToInt(Order::totalCents).sum(), which does the same without a combiner to get wrong.Use the three-argument form when no ready-made terminal operation fits and the partial results are immutable values. Otherwise the same three roles (supplier, accumulator, combiner) are in
collect, which is built for mutable containers.If you cannot say what the combiner does in one sentence, step back and use a collector.
- "Why is reduce with String concatenation slow, and what should I use?"
-
A
Stringis immutable, so everya + ballocates a new string and copies both. In a loop of N steps the total copying grows with the square of N. The demo with 20,000 numbers took 778 ms byreduceand 4 ms byjoining, almost two hundred times slower, and the gap widens with size.Collectors.joining(", ")uses oneStringBuilderper thread, so it is linear. For a stream of strings,String.join(",", list)is the simplest form when you already have a list.The same trap exists in plain loops:
s += xin a loop is the quadratic version, andStringBuilderis the fix. A stream does not change the cost of the operation you give it.Review rule: any
reducethat builds a collection or a string deserves a second look. - "Can I use reduce to compute an average or a count with a sum?"
-
Only with care. A plain
reducecomputes one value of one type. An average needs a sum and a count together, so it needs two values. You can fake it with a small record holding both, and an associative combine, but then you are writing a collector by hand.The built-in answers are better:
averagingInt,summarizingInt(count, sum, min, average, max in one pass),mapToInt(...).average()andteeingto run two collectors and merge them (question 49).If you must write your own, give the record an
addand amergeand usecollect, as the custom collector in question 53 does.Remember also the empty case:
reduce(Integer::sum)with no identity returns anOptionalbecause there may be no elements, whilereduce(0, Integer::sum)returns 0.
Q41. "Why do IntStream and LongStream exist? Show the boxing cost."
Reveal answer
Strong answer A Stream<Integer> holds objects. Each number is wrapped in an Integer, which is a separate heap object with a header, 16 bytes in a typical JVM, plus a 4-byte reference to it in the list or pipeline. An IntStream holds plain int values with no wrapper.
The wrapping costs in three ways. Memory: five million boxed integers take around 100 MB compared with 20 MB for an int[]. Speed: every operation unboxes the object to do arithmetic and boxes the answer again, creating garbage. Cache: the objects are scattered in memory, so the CPU cannot read them sequentially.
The primitive streams (IntStream, LongStream, DoubleStream) avoid all three. They also add useful terminal operations that the generic stream lacks: sum(), average(), min(), max() and summaryStatistics(), plus range and rangeClosed as a loop replacement.
Convert with mapToInt, mapToLong, mapToDouble (object to primitive), boxed() (primitive to object) and asLongStream(). Rule: in a pipeline over numbers, switch to a primitive stream as early as possible with mapToInt, and stay there.
There is no ShortStream or FloatStream; use IntStream and DoubleStream for those.
Picture it Five million numbers summed three ways: boxed objects with reduce, boxed objects with mapToLong, and a primitive array.
The setup: Q41_Boxing.java generates 5,000,000 numbers with new Random(42), as an int[] and as a List<Integer>. It runs three rounds of three versions so that the JIT compiler has warmed up by round two. The program runs with -Xmx512m.
import java.util.*;
import java.util.stream.*;
public class Q41_Boxing {
public static void main(String[] args) {
Random rnd = new Random(42);
int[] prim = new int[5_000_000];
for (int i = 0; i < prim.length; i++) prim[i] = rnd.nextInt(1000);
List<Integer> boxed = Arrays.stream(prim).boxed().toList(); // 5,000,000 Integer objects
for (int round = 1; round <= 3; round++) { // 3 rounds so the JIT has warmed up
long t0 = System.nanoTime();
long a = boxed.stream().map(x -> x * 2L).reduce(0L, Long::sum); // Integer -> Long -> Long
long t1 = System.nanoTime();
long b = boxed.stream().mapToLong(x -> x * 2L).sum(); // unbox once, then primitives
long t2 = System.nanoTime();
long c = Arrays.stream(prim).asLongStream().map(x -> x * 2).sum(); // primitive array, no objects
long t3 = System.nanoTime();
System.out.printf("round %d: boxed reduce %4d ms | mapToLong %4d ms | int[] source %4d ms | equal=%b%n",
round, (t1 - t0) / 1_000_000, (t2 - t1) / 1_000_000, (t3 - t2) / 1_000_000, a == b && b == c);
}
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
System.out.println("sum of 5,000,000 values: " + IntStream.of(prim).asLongStream().sum());
IntSummaryStatistics st = IntStream.of(prim).summaryStatistics();
System.out.println(st);
}
}Make the invisible visible: Run it.
round 1: boxed reduce 114 ms | mapToLong 30 ms | int[] source 57 ms | equal=true
round 2: boxed reduce 82 ms | mapToLong 13 ms | int[] source 1 ms | equal=true
round 3: boxed reduce 83 ms | mapToLong 14 ms | int[] source 1 ms | equal=true
// measured on the course machine (12 cores); your numbers will differ
sum of 5,000,000 values: 2497124277
IntSummaryStatistics{count=5000000, sum=2497124277, min=0, average=499.424855, max=999}What you see: After warm-up, the version that stays boxed (map to Long then reduce) takes about 82 ms. Unboxing once with mapToLong takes about 13 ms, six times faster. Reading straight from the int[] took 1 ms, because there are no objects to touch and the JIT can use vector instructions. All three agree on the answer. summaryStatistics() gives the whole picture in one pass.
Why: The boxed pipeline has to chase 5 million references and create new Long objects as it goes. The primitive pipeline walks a flat array.
Boxed
An object per number.
long total = list.stream()
.map(n -> n * 2L) // Long objects
.reduce(0L, Long::sum);Primitive
Plain numbers.
long total = list.stream()
.mapToLong(n -> n * 2L)
.sum();The shift: mapToLong unboxes once and everything after it works on plain numbers.
Land it IntStream, LongStream and DoubleStream hold plain numbers, so a pipeline over numbers should switch to them early with mapToInt to avoid an object per element.
- "Is the speed-up always this large?"
-
No. This measurement is a tight loop of simple arithmetic over a very large data set, which is the worst case for boxing. For a list of a few hundred orders where each step calls a database or builds a string, the boxing cost is lost in the noise.
The speed-up also depends on the JIT compiler. After warm-up it can remove some boxing with escape analysis, which is why the first round in the output was slower for everything. Benchmarks that run once mislead. Use JMH for serious numbers.
The memory saving is the more reliable gain. A
List<Integer>of five million entries is about five times the size of anint[], which affects garbage collection and cache, even if time per element looks similar.My rule: use primitive streams as a habit, since it costs nothing and reads as well. Do not rewrite working code for speed unless a profile points at it.
- "What extra methods do primitive streams give me?"
-
sum(),average()(returns anOptionalDouble),min()andmax()(OptionalIntand friends),count()andsummaryStatistics(), which returns count, sum, min, average and max in one pass. The genericStreamhas none of these, so you would needreduceor a collector.Also factories:
IntStream.range(0, n)(excludes the end),rangeClosed(1, n)(includes it),IntStream.of(...),Arrays.stream(int[]), andString.chars(), which gives anIntStreamof characters.rangeis the clean replacement for an indexed loop:IntStream.range(0, list.size()).filter(i -> ...)when you need the index.When you need the object form again, for example to collect into a
List, callboxed()ormapToObj(...). That is the one place boxing is unavoidable. - "What are the common traps with primitive streams?"
-
First,
average()andmax()on an empty stream return an emptyOptional, not zero, so callorElse(0)or handle it.sum()returns 0 for an empty stream, which hides the missing-data case.Second, overflow:
IntStream.sum()returns anintand silently wraps around past 2.1 billion. For totals in paise across many orders, usemapToLong. The demo's total of 2.49 billion would have overflowed an int, which is why it useslong.Third,
boxed()in the middle of a pipeline throws away the benefit. Boxing, thenfilteron objects, then unboxing again is slower than staying primitive.Fourth,
IntStream.range(0, n).parallel()splits well, butiterateandgeneratesources split poorly (question 58). - "Can I avoid boxing in collections too?"
-
The JDK collections only hold objects. If boxing really hurts, for millions of numbers, the options are an
int[](orlong[],double[]) used directly, or a library with primitive collections: Eclipse Collections (IntList,IntIntMap), fastutil, or HPPC.For streams, avoid putting numbers in a list at all. Compute them directly from the source as an
IntStream, then usesumorcollect. If you need to store results,stream.toArray()on anIntStreamgives anint[].Project Valhalla aims to let generics hold primitive-like value types in the future, which would remove the problem. As I write this, that is planned and not available (check the JDK 28 notes).
For ordinary services with lists of a few thousand numbers, none of this matters. It matters for analytics code and hot loops.
Q42 · Scenario. "A stream adds to an external list inside forEach and sometimes gives wrong results. Fix it."
Reveal answer
Strong answer The pipeline has a side effect on shared state: the lambda adds to an ArrayList that lives outside the stream. On a sequential stream that works, so the code passes tests.
On a parallel stream, several worker threads call add on the same ArrayList at the same time. ArrayList is not thread-safe: two threads can write to the same slot, or one can grow the backing array while another writes into the old one. The result is lost elements, null holes, or an ArrayIndexOutOfBoundsException, and different on each run.
The same happens if someone adds .parallel() later, or if a framework does it for you. The bug was always there. Parallelism only exposed it.
Fix: let the stream build the result. source.parallelStream().filter(...).toList() or .collect(Collectors.toList()). Each worker fills a private container and the library merges them in order. For counts and sums use count(), sum() or summingInt.
What not to do: do not swap in Collections.synchronizedList or CopyOnWriteArrayList as the cure. It makes the list safe, but the order of elements is no longer the stream order, and the lock makes parallelism slow.
The rule behind it: lambdas in a pipeline must be stateless and non-interfering. Results leave the pipeline through the terminal operation, not through variables the lambdas poke from outside.
Picture it A sequential run that works, five parallel runs of the broken version, and the fixed versions.
The setup: Q42_SideEffects.java filters the even numbers from 100,000 integers (expected 50,000). It first adds to an external ArrayList from a sequential forEach, then does the same from parallelStream().forEach five times, then uses toList() and count().
import java.util.*;
import java.util.stream.*;
public class Q42_SideEffects {
public static void main(String[] args) {
List<Integer> source = IntStream.range(0, 100_000).boxed().toList();
List<Integer> seq = new ArrayList<>();
source.stream().filter(n -> n % 2 == 0).forEach(seq::add); // works only because it is sequential
System.out.println("sequential forEach/add: " + seq.size() + " (expected 50000)");
for (int run = 1; run <= 5; run++) {
List<Integer> shared = new ArrayList<>();
String result;
try {
source.parallelStream().filter(n -> n % 2 == 0).forEach(shared::add); // BUG: ArrayList is not thread-safe
result = shared.size() + " elements, " + (shared.contains(null) ? "contains null" : "no nulls");
} catch (RuntimeException e) { result = e.toString(); }
System.out.println("run " + run + " parallel forEach/add: " + result);
}
List<Integer> fixed = source.parallelStream().filter(n -> n % 2 == 0).toList(); // FIX: let the stream collect
System.out.println("parallel toList(): " + fixed.size() + ", first " + fixed.get(0) + ", last " + fixed.get(fixed.size() - 1));
long evens = source.parallelStream().filter(n -> n % 2 == 0).count();
System.out.println("or just count(): " + evens);
}
}Make the invisible visible: Run it.
sequential forEach/add: 50000 (expected 50000)
run 1 parallel forEach/add: 41536 elements, no nulls
run 2 parallel forEach/add: 14349 elements, contains null
run 3 parallel forEach/add: 2305 elements, no nulls
run 4 parallel forEach/add: 16309 elements, contains null
run 5 parallel forEach/add: 21826 elements, contains null
parallel toList(): 50000, first 0, last 99998
or just count(): 50000What you see: Sequential gave exactly 50,000. The five parallel runs gave 41,536, 14,349, 2,305, 16,309 and 21,826 elements; three of them also contained null entries. The corrected toList() returned 50,000 with the right first and last values (0 and 99,998), and count() agreed.
Why: One thread's add overwrote another's, or resized the array while another thread was writing. The result is not just short, it is wrong in different ways each time.
Side effect
Writes to shared state.
List<Integer> out = new ArrayList<>();
nums.parallelStream()
.filter(n -> n % 2 == 0)
.forEach(out::add); // raceCollect
The stream returns the result.
List<Integer> out = nums.parallelStream()
.filter(n -> n % 2 == 0)
.toList();The shift: The list is built by the pipeline's own safe machinery instead of by all threads writing to one object.
Land it The lambda wrote to a shared ArrayList, so I let the stream produce the list with toList or collect, because pipeline lambdas must not touch outside state.
- "Why not just use a synchronized or concurrent list?"
-
A synchronized list stops the data corruption, but it fixes the symptom with a lock. Every
addtakes the same lock, so the workers queue up for it, and the parallel stream can be slower than a sequential one. The order of elements also depends on which thread got the lock, so it no longer matches the source order.A
CopyOnWriteArrayListis worse here: everyaddcopies the whole array, so adding 50,000 elements is quadratic. It is built for rarely changing, often read lists, such as listeners.ConcurrentLinkedQueueor a concurrent set avoid the lock, and are correct, but they still lose order. If you need a set of results,Collectors.toSet()orgroupingByConcurrentuse the concurrent structures properly for you.The better principle is that collectors exist so that nobody else has to share state. Choose the collector first, and a concurrent structure only if no collector fits.
- "Is forEach with a side effect ever acceptable?"
-
Yes, at the end of a pipeline for a real effect, such as printing, sending a message or saving a row, as long as the effect is safe to run from several threads in any order, or the stream is sequential.
forEach(order -> mailer.send(order))is fine if the mailer is thread-safe and you do not care about order. It is the terminal operation and its job is the side effect.What is not fine is using the side effect to return a result through an outside variable, or doing effects in
map,filterorpeek, where they may run in surprising numbers and orders (question 34).For ordered effects in a parallel stream,
forEachOrderedmakes the action run in encounter order, at a speed cost (question 59). Or run the stream sequentially, which is the right call for anything that must happen in order.If the effect throws a checked exception, a plain loop is usually clearer (question 45).
- "How do I count or sum safely while streaming?"
-
Use the terminal operations designed for it:
count(),sum(),average()andcollect(Collectors.counting()),summingInt,summarizingInt. They give each thread a private partial total and combine the totals at the end. No sharing, no lock, no wrong answers.If you need counts by group,
groupingBy(key, counting())does it in one pass, andgroupingByConcurrentuses a shared concurrent map for parallel speed when the order of results does not matter.If you truly must update a shared counter from inside a lambda, such as progress reporting, use
LongAdderorAtomicLong. They are safe and fast under contention (chapter section 09 measures it). Never a plainintorlong: the demo in question 56 shows a sharedlonglosing most of its sum.A good test of any parallel code: run it twenty times and compare the results. Race bugs usually show up within a few runs.
- "How do I find this kind of bug in an existing code base?"
-
Search for
forEach(andpeek(whose lambda body callsadd,put,appendor++on a variable declared outside the lambda. Most IDEs and static analysers (IntelliJ's "stream API call chain can be simplified" and the Error Prone checks) flag the pattern, and SonarQube has a rule for modifying a collection from within a stream.Next, search for
.parallel()andparallelStream(). Every such pipeline deserves a second look at its lambdas, and a measurement that proves it is worth being parallel (question 58).In tests, run any parallel pipeline many times, and with a large input. A race condition rarely shows with a 10-element list. The demo used 100,000 elements and lost data in every run.
Finally, give team guidance: "streams return results; they do not fill variables".
Q43. "toList() (16) versus collect(Collectors.toList()) — what is different?"
Reveal answer
Strong answer Four differences, one of them important.
1. Mutability. Stream.toList() returns an unmodifiable list: add, remove and set throw UnsupportedOperationException. collect(Collectors.toList()) returns a list whose type, mutability and thread-safety are not specified by the Javadoc. In practice today it is an ArrayList that you can change, which is why so much code changes it and breaks when switched to toList().
2. Nulls. toList() accepts null elements. So does collect(toList()). (Collectors.toUnmodifiableList() and List.of reject them.)
3. Length and readability. toList() is shorter and needs no import. It exists since Java 16.
4. Efficiency. toList() can skip a copy: if the stream knows its size, it fills one array and wraps it. collect grows an ArrayList and may resize.
When to use which: toList() as the default at the end of a pipeline when you do not need to change the result. collect(Collectors.toCollection(ArrayList::new)) when you want a mutable list and want the code to say so. Avoid collect(Collectors.toList()) in new code, since it hides the very property you care about.
Migration warning: replacing collect(toList()) with toList() across a code base can break callers that add to the result. Run the tests, and read the failures as a list of places that mutated a list they did not own.
Picture it Two lists from the same stream, probed for add and set, plus the class names and the null behaviour.
The setup: Q43_ToList.java builds a list each way, tries add and set on both, prints their classes, then checks null handling and shows how to get a mutable copy.
import java.util.*;
import java.util.stream.*;
public class Q43_ToList {
static String probe(List<String> l, String what) {
try { if (what.equals("add")) l.add("x"); else l.set(0, "x"); return "ok"; }
catch (UnsupportedOperationException e) { return "UnsupportedOperationException"; }
}
public static void main(String[] args) {
List<String> a = Stream.of("dosa", "idli").toList();
List<String> b = Stream.of("dosa", "idli").collect(Collectors.toList());
System.out.println("toList() add: " + probe(a, "add") + ", set: " + probe(a, "set"));
System.out.println("collect(toList()) add: " + probe(b, "add") + ", set: " + probe(b, "set"));
System.out.println("classes: " + a.getClass().getName() + " | " + b.getClass().getName());
System.out.println("nulls: toList " + Stream.of("a", null).toList()
+ ", List.of would throw, Collectors.toUnmodifiableList would throw:");
try { Stream.of("a", null).collect(Collectors.toUnmodifiableList()); } catch (NullPointerException e) { System.out.println(" NPE"); }
System.out.println("equal contents are equal: " + a.equals(List.of("dosa", "idli")));
List<String> viaList = new ArrayList<>(a);
viaList.add("vada");
System.out.println("mutable copy when you need one: " + viaList);
Set<String> set = Stream.of("a", "a").collect(Collectors.toSet());
System.out.println("toSet is a " + set.getClass().getSimpleName() + ", no toSet() on Stream");
}
}Make the invisible visible: Run it.
toList() add: UnsupportedOperationException, set: UnsupportedOperationException
collect(toList()) add: ok, set: ok
classes: java.util.ImmutableCollections$ListN | java.util.ArrayList
nulls: toList [a, null], List.of would throw, Collectors.toUnmodifiableList would throw:
NPE
equal contents are equal: true
mutable copy when you need one: [dosa, idli, vada]
toSet is a HashSet, no toSet() on StreamWhat you see: toList() refused both add and set, and its class is an internal immutable list (ImmutableCollections$ListN). collect(toList()) allowed both and is a plain ArrayList. toList() accepted a null element, while toUnmodifiableList() threw an NPE. Wrapping the result in new ArrayList<>(...) gave a mutable copy.
Why: The two methods answer different promises. toList() promises "unmodifiable", and toList from Collectors promises nothing, so it happens to be mutable.
Java 8 style
Mutable by accident.
List<String> names = orders.stream()
.map(Order::customer)
.collect(Collectors.toList());
names.add("extra"); // works todayJava 16 style
Unmodifiable on purpose.
List<String> names = orders.stream()
.map(Order::customer)
.toList();
names.add("extra"); // throws UOEThe shift: The newer call says what you get, and code that needs a mutable list has to ask for one.
Land it toList returns an unmodifiable list on purpose, while collect with Collectors.toList promises nothing and happens to give a mutable ArrayList, so I use toList by default and ask for a mutable list explicitly when I need one.
- "My code broke after I switched to toList(). Why?"
-
Somewhere a caller adds to, sorts or removes from the returned list. That worked when the list was an
ArrayListand now throwsUnsupportedOperationException. The call that fails may be far from the one you changed, because the list travelled through other methods.Sorting is the common one:
names.sort(...)orCollections.sort(names)modifies the list in place, so it fails on an unmodifiable list. The fix is to sort in the stream (.sorted().toList()) or to copy first (new ArrayList<>(names)).The failure is useful. It shows places where code modified a list it did not own. Fix them by copying at that point, which makes the ownership explicit.
If you do not have time, keep
Collectors.toCollection(ArrayList::new)in the places that need a mutable list. That is a clear statement of intent that survives future refactors. - "Is the list from toList() thread-safe or deeply immutable?"
-
Neither of those claims is made. It is unmodifiable: the list object refuses structural and element changes through its own methods. If the elements are mutable objects, anyone holding one of them can change it, and the list will show the change.
Because the list cannot change, it is safe to read from several threads once it has been safely published to them. That is true of any unmodifiable list. It does not make the elements themselves thread-safe.
It is also not the same class as
List.of's result in every detail.List.ofrejects nulls andtoList()allows them.Records and immutable value objects as elements give you the deep immutability. A list of unmodifiable lists of strings is deeply immutable. A list of
StringBuilderis not. - "When should I still use collect(Collectors.toList())?"
-
When you need to support Java 8 to 15, since
toList()does not exist there. A library that targets Java 8 must keep the old form.Also as the downstream collector inside
groupingByandpartitioningBy:groupingBy(Order::restaurant, mapping(Order::id, toList()))usesCollectors.toList()becauseStream.toList()is a stream method and cannot be used as a collector. Here it means "collect each group into a list", and the lists inside the map are mutable in practice.And when you really want a mutable result and you are happy to rely on the implementation. I prefer
toCollection(ArrayList::new)in that case, since it states the guarantee.For the common terminal case, in new code on Java 16 or later, use
toList(). - "How do toList(), toUnmodifiableList() and copyOf compare?"
-
Stream.toList(): unmodifiable, nulls allowed, shortest.Collectors.toUnmodifiableList()(10): unmodifiable, nulls rejected, usable as a downstream collector.List.copyOf(collection)(10): unmodifiable copy, nulls rejected, works on any collection and returns the argument itself if it is already an immutable list.In other words: use
toList()at the end of a stream,toUnmodifiableList()insidegroupingBywhen you want immutable groups, andcopyOfto protect a field or parameter from later changes (question 12).All three give a list that refuses changes. The differences are whether nulls get in and where you can write the call.
Question 52 lists the unmodifiable collectors in full.
Q44. "takeWhile/dropWhile (9) versus filter."
Reveal answer
Strong answer filter(p) looks at every element and keeps those where p is true. takeWhile(p) keeps elements from the start and stops at the first element where p is false, and it ignores everything after that, even elements that would pass. dropWhile(p) is the mirror: it discards elements from the start while p is true and then keeps everything from the first failure to the end, with no further checking.
So they answer different questions. filter: "which elements match?". takeWhile: "what is the prefix that matches?". dropWhile: "what is left after the prefix that matches?".
When takeWhile wins: the data is sorted or otherwise ordered by the condition. "Orders cheaper than ₹300 in a list sorted by price" is a prefix. takeWhile stops at the first expensive order, while filter would scan all of them. On an infinite stream, only takeWhile can end: iterate(1, i -> i * 2).takeWhile(i -> i < 100).
When takeWhile is a bug: on unsorted data. The first element may fail the test and takeWhile returns an empty result, while filter finds the matches further down. In the demo, the unsorted list starts with a ₹547 order and takeWhile(x < 30000) returns nothing.
Good uses: log lines until the first error, sorted data windows, infinite generators, and a header section of a file.
Picture it The same cheap-order test with filter and takeWhile on sorted and unsorted order totals, counting how many elements each looked at.
The setup: Q44_TakeWhile.java sorts the twelve order totals, then applies filter and takeWhile with a peek counter. It repeats on the unsorted list, shows dropWhile, and ends with an infinite stream and a log-lines example.
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.*;
public class Q44_TakeWhile {
public static void main(String[] args) {
List<Integer> sortedTotals = Data.ORDERS.stream().map(Order::totalCents).sorted().toList();
System.out.println("sorted totals: " + sortedTotals);
var checkedA = new AtomicInteger(); var checkedB = new AtomicInteger();
List<Integer> cheap1 = sortedTotals.stream().peek(x -> checkedA.incrementAndGet()).filter(x -> x < 30000).toList();
List<Integer> cheap2 = sortedTotals.stream().peek(x -> checkedB.incrementAndGet()).takeWhile(x -> x < 30000).toList();
System.out.println("filter -> " + cheap1 + " looked at " + checkedA);
System.out.println("takeWhile -> " + cheap2 + " looked at " + checkedB);
List<Integer> unsorted = Data.ORDERS.stream().map(Order::totalCents).toList();
System.out.println("unsorted filter : " + unsorted.stream().filter(x -> x < 30000).toList());
System.out.println("unsorted takeWhile : " + unsorted.stream().takeWhile(x -> x < 30000).toList() + " <- stops at the first miss");
System.out.println("unsorted dropWhile : " + unsorted.stream().dropWhile(x -> x < 60000).toList());
System.out.println("infinite: " + Stream.iterate(1, i -> i * 2).takeWhile(i -> i < 100).toList());
System.out.println("log lines until ERROR: " + Stream.of("ok", "ok", "ERROR", "ok").takeWhile(s -> !s.equals("ERROR")).toList());
}
}Make the invisible visible: Run it.
sorted totals: [21900, 23800, 24900, 27400, 27600, 29700, 34900, 46900, 54700, 68700, 79800, 89400]
filter -> [21900, 23800, 24900, 27400, 27600, 29700] looked at 12
takeWhile -> [21900, 23800, 24900, 27400, 27600, 29700] looked at 7
unsorted filter : [29700, 21900, 27400, 24900, 27600, 23800]
unsorted takeWhile : [] <- stops at the first miss
unsorted dropWhile : [79800, 27600, 89400, 34900, 23800, 68700]
infinite: [1, 2, 4, 8, 16, 32, 64]
log lines until ERROR: [ok, ok]What you see: On sorted data both methods found the same six cheap totals, but filter looked at all 12 elements and takeWhile looked at 7 (the six matches plus the first miss, 34,900). On the unsorted list filter found the six cheap orders and takeWhile found [], because the first element (54,700) already failed the test. dropWhile(x < 60000) discarded the prefix and kept everything from 79,800 on, including values that would fail the test. The infinite powers of two stopped at 64.
Why: takeWhile trusts the order of the data. It stops at the first failure, so it is only the same as filter when everything that passes comes before everything that fails.
filter
Scans every element.
sortedTotals.stream()
.filter(x -> x < 30000)
.toList();
// looked at all 12 elementstakeWhile
Stops at the first miss.
sortedTotals.stream()
.takeWhile(x -> x < 30000)
.toList();
// looked at 7 elementsThe shift: On sorted data takeWhile gives the same answer by reading only the prefix.
Land it filter checks every element, takeWhile and dropWhile act on a prefix, so I use them only on ordered data or infinite streams and otherwise stay with filter.
- "What is the risk of takeWhile on data I think is sorted?"
-
If the data is not sorted the way you think, you get a short, wrong result with no error. A list that arrives from a database without
ORDER BY, a map's values, or a parallel stream's output can all be in a different order than you assumed. The code works in a test with sorted sample data, and returns too little in production.Protect against it by sorting in the pipeline (
sorted()beforetakeWhile), at the cost of a full sort, or by keepingfilterwhen you are not sure of the order.filteris always correct,takeWhileis only correct for ordered data.Also, on a parallel unordered stream,
takeWhileis allowed to return any subset that satisfies the rule, which is rarely what you want. Use it on sequential, ordered streams.My habit: reach for
takeWhileonly with a comment that names the ordering it depends on. - "What is the three-argument Stream.iterate and how does it compare?"
-
Java 9 added
Stream.iterate(seed, hasNext, next), a stream version of aforloop: start value, condition to continue, step.Stream.iterate(1, i -> i <= 100, i -> i * 3)gives 1, 3, 9, 27, 81, as the output in question 36 showed.It produces a finite stream directly, so it replaces the older "infinite
iterateplustakeWhile" in many cases. The two-argument form withtakeWhileis still useful when the stop condition belongs to a later part of the pipeline.Both have the same limit on parallel speed:
iterateproduces elements in order, one after another, so it splits badly (question 58).For a numeric range,
IntStream.rangeis simpler and splits well. Useiteratewhen each element depends on the previous one, such as a doubling sequence or a linked-list walk. - "When is dropWhile useful?"
-
For skipping a header or a leading section. A log file whose first lines are comments:
lines.dropWhile(l -> l.startsWith("#"))removes the leading comment block and keeps all the rest, even a later line that starts with "#", which is probably what you want.With sorted data: "everything after the cheap orders" is
dropWhile(x -> x < 30000). It avoids testing the remaining elements.It is the same prefix logic as
takeWhile, so the same rule applies: only use it when the prefix is well defined. In the demo,dropWhile(x -> x < 60000)on the unsorted list kept 79,800 and the elements after it, even 27,600, which is below 60,000. That is correct behaviour, and surprising if you expected a filter.Compare with
skip(n), which drops a fixed count, andfilter, which drops by condition everywhere. - "How do these behave in parallel streams?"
-
Badly in terms of speed, and carefully in terms of results. On an ordered parallel stream,
takeWhileanddropWhilestill return the same result as the sequential version (the prefix in encounter order), but the library has to coordinate between chunks, because a chunk cannot know whether the prefix has already ended in an earlier chunk. That often makes parallel slower than sequential.On an unordered stream the result is allowed to be any valid answer, which for these two operations means unpredictable output.
So: use sequential streams for prefix operations. If the data set is big enough to want parallelism, consider whether a loop with a binary search on sorted data (
Collections.binarySearch) is better. That is O(log n) instead of scanning at all.The general lesson is the one from question 37: operations that depend on position are the ones that parallelise worst.
Q45. "Is stream().forEach the same as a for loop? When is the loop better?"
Reveal answer
Strong answer For simple, independent work on a sequential stream the two do the same thing. But they are not the same tool, and the differences matter.
Where the loop is better. First, checked exceptions: a lambda inside forEach cannot throw IOException or SQLException, so you wrap it in a try-catch that rethrows an unchecked exception. A loop just lets the exception through. Second, early exit: a loop can break, continue or return from the method.
Inside a lambda return only leaves the lambda, so forEach(x -> { if (bad) return; }) is a continue, not a method return. Third, changing local variables: a lambda can only read effectively final locals (question 28), a loop can update them. Fourth, index arithmetic and walking two lists together. Fifth, debugging: stepping through a loop is simpler than through the stream internals, and stack traces are much shorter.
Where the stream is better. A pipeline of filter, map and collect reads as the description of the result, with no mutable accumulator and no index, and it can be made parallel later if a measurement shows it helps. For building a new collection or a total from another, the stream is usually clearer.
Differences in contract. forEach on a parallel stream runs in any order. Iterable.forEach on a list is a loop in order. And stream().forEach(...) on a collection adds nothing over list.forEach(...) unless you need a stream stage before it.
My rule: use a stream when the result is a value or a collection built from the data. Use a loop when the point is the side effect, the control flow or the error handling.
Picture it The same revenue total both ways, then a checked exception and an early return, where the loop is natural and the stream needs workarounds.
The setup: Q45_LoopVsStream.java sums delivered Bengaluru revenue with a loop and a stream. It then prints "tickets" for four orders with a method that throws a checked IOException for order 3, once in a loop and once inside forEach, and finally finds the first large cancelled order with an early return.
import java.io.IOException;
import java.util.*;
import java.util.stream.*;
public class Q45_LoopVsStream {
static String check(Order o) throws IOException {
if (o.id() == 3) throw new IOException("kitchen printer offline for order 3");
return "printed " + o.id();
}
static Optional<Order> firstBigCancelled() { // early return: natural in a loop
for (Order o : Data.ORDERS) if (o.status().equals("CANCELLED") && o.totalCents() > 30000) return Optional.of(o);
return Optional.empty();
}
public static void main(String[] args) {
// same answer, both ways
int loopSum = 0;
for (Order o : Data.ORDERS)
if (o.status().equals("DELIVERED") && o.city().equals("Bengaluru")) loopSum += o.totalCents();
int streamSum = Data.ORDERS.stream()
.filter(o -> o.status().equals("DELIVERED") && o.city().equals("Bengaluru"))
.mapToInt(Order::totalCents).sum();
System.out.println("loop " + loopSum + " stream " + streamSum);
// checked exception: easy in a loop, awkward in a lambda
try {
for (Order o : Data.ORDERS.subList(0, 4)) System.out.println(check(o));
} catch (IOException e) { System.out.println("loop stopped: " + e.getMessage()); }
try {
Data.ORDERS.subList(0, 4).stream().forEach(o -> {
try { System.out.println(check(o)); } catch (IOException e) { throw new RuntimeException(e); } // wrapper noise
});
} catch (RuntimeException e) { System.out.println("stream stopped: " + e); }
System.out.println("early return: " + firstBigCancelled().map(Order::id).orElse(-1));
}
}Make the invisible visible: Run it.
loop 183800 stream 183800
printed 1
printed 2
loop stopped: kitchen printer offline for order 3
printed 1
printed 2
stream stopped: java.lang.RuntimeException: java.io.IOException: kitchen printer offline for order 3
early return: 10What you see: Both give 183,800. In the loop, the checked exception simply stopped the work with a clear message after orders 1 and 2. Inside the stream it had to be wrapped in a RuntimeException, and the stopped result reads java.lang.RuntimeException: java.io.IOException: ..., an extra layer of noise. The early-return search found order 10 without any wrapper.
Why: A lambda is a separate method. It cannot return from the method around it and cannot throw its checked exceptions, so control flow is limited.
for loop
Control flow is free.
for (Order o : orders) {
if (o.id() == 3) continue;
print(o); // may throw IOException
if (done(o)) return;
}forEach
A lambda cannot do those.
orders.forEach(o -> {
if (o.id() == 3) return; // only a continue
try { print(o); }
catch (IOException e) {
throw new UncheckedIOException(e);
}
});The shift: Inside a lambda, return means "end this call", and checked exceptions must be wrapped.
Land it A stream is better for building a result from data, and a loop is better when I need checked exceptions, early exit, changing locals or step-through debugging.
- "Is a for loop faster than a stream?"
-
For small and medium inputs the difference is negligible, and both are fast. For a hot loop over millions of primitives, a plain loop over an
int[]is faster than a boxed stream, and similar to a primitive stream after JIT warm-up (question 41 measured 1 ms against 13 ms for boxed-to-mapToLong).Streams add object allocation for the pipeline stages and virtual calls through lambdas. The JIT often inlines them, but not always.
Do not choose by speed unless a profile says so. Choose by clarity. If you profile and find a stream in a hot path, rewrite that one piece as a loop, and leave the comment explaining why.
Most real services spend their time in the database and the network, not in the choice between a loop and a stream.
- "Why does forEach on a parallel stream not keep order?"
-
The stream splits the data into parts and different threads process them at the same time. Each thread calls your action when it reaches an element. Thread A may be at element 5 while thread B is at element 800.
forEachmakes no promise about the order of calls, only that each element is processed once.forEachOrderedpromises encounter order, at a cost: threads that finished early wait for the earlier elements to be done (question 59 measured 102 ms against 1,210 ms for a sleep-heavy action).The sequential
forEachon an ordered source such as a list does process in order, but the documentation still does not promise it. If order matters, writeforEachOrderedor use a loop, so the intent is clear.Printing from a parallel
forEachis the classic demo of this. Output appears in a different order on every run. - "How do I handle checked exceptions in a stream pipeline?"
-
Four options. Wrap in the lambda: catch and rethrow as
UncheckedIOExceptionorRuntimeException, as the demo does. It works and is noisy. Extract a method: a private method that catches and converts, then use a method reference (.map(this::readSafely)). It keeps the pipeline clean.Return a result type: have the mapping function return an
Optionalor a smallResultrecord instead of throwing, then filter the failures. This is good when you want to keep going and report errors at the end.Use a loop: when the failure should stop everything and you want the original exception type to reach the caller, a loop is simplest.
What not to do is a generic "sneaky throw" helper that hides a checked exception from the compiler. It works, and it surprises callers who cannot catch the exception by type.
- "When would I mix the two?"
-
All the time, and that is fine. A common shape: use a stream to build the data (filter, map, collect), then a loop to act on it with full control flow. Or use a loop to read and validate input with checked exceptions, and a stream to summarise the validated list.
Within a method, one loop with several statements is often clearer than three chained pipelines that each re-read the same list. Do not feel obliged to convert every loop. Streams are a tool, not a style requirement.
A useful smell test: if a lambda in a stream grows beyond three lines, or needs a comment to explain what it does, move it to a named method or turn the stage into a loop.
In code review, I accept both, and ask only that the choice be for a reason: result building, or control flow.
These nine questions are about the terminal operations that build maps, groups, partitions and summaries, and when a hand-written collector or a database query is the better answer.
Q46. "groupingBy with downstream collectors: count orders per restaurant and revenue per day."
Reveal answer
Strong answer groupingBy(classifier) sorts elements into buckets: it calls the classifier on each element and uses the result as the map key. By default, each bucket is a List of the elements that got that key. The result is a Map<Key, List<T>>.
The downstream collector is a second argument that says what to do with each bucket instead of collecting a list. groupingBy(Order::restaurant, counting()) counts the orders in each bucket and gives a Map<String, Long>. groupingBy(Order::day, summingInt(Order::totalCents)) adds the totals per day and gives a Map<String, Integer>.
Common downstream collectors: counting(), summingInt/Long/Double, averagingInt, summarizingInt, mapping(f, downstream) (transform before collecting), filtering(p, downstream), flatMapping, maxBy, minBy, joining, toSet and another groupingBy for two levels.
The three-argument form groupingBy(classifier, mapFactory, downstream) chooses the map type: TreeMap::new for sorted keys, LinkedHashMap::new for first-seen order. The default map is a HashMap, with no order guarantee.
Two behaviours to remember. A key is never null (the classifier must not return null, or you get a NullPointerException). And a bucket exists only if at least one element fell into it, so an empty bucket does not appear (use filtering when you need zero entries, question 51).
Picture it Four grouping questions on the QuickBite orders, including delivered revenue per day in sorted order and a two-level count.
The setup: Q46_GroupingBy.java groups ids per restaurant, counts orders per restaurant, totals delivered revenue per day into a TreeMap, averages the order value per city, and builds a nested day by restaurant count.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q46_GroupingBy {
public static void main(String[] args) {
// one-argument groupingBy: key -> List of the elements
Map<String, List<Integer>> ids = Data.ORDERS.stream().collect(groupingBy(Order::restaurant, mapping(Order::id, toList())));
System.out.println("ids per restaurant : " + ids);
// downstream collector: what to do with each bucket
Map<String, Long> perRestaurant = Data.ORDERS.stream().collect(groupingBy(Order::restaurant, counting()));
System.out.println("orders per restaurant : " + perRestaurant);
Map<String, Integer> revenuePerDay = Data.ORDERS.stream()
.filter(o -> o.status().equals("DELIVERED"))
.collect(groupingBy(Order::day, TreeMap::new, summingInt(Order::totalCents)));
System.out.println("delivered rev per day : " + revenuePerDay);
Map<String, Double> avg = Data.ORDERS.stream().collect(groupingBy(Order::city, TreeMap::new, averagingInt(Order::totalCents)));
System.out.println("average order per city : " + avg);
// nested: day -> restaurant -> count
Map<String, Map<String, Long>> nested = Data.ORDERS.stream()
.collect(groupingBy(Order::day, TreeMap::new, groupingBy(Order::restaurant, TreeMap::new, counting())));
nested.forEach((day, m) -> System.out.println(" " + day + " " + m));
}
}Make the invisible visible: Run it.
ids per restaurant : {Spice Hut=[1, 3, 6, 9, 12], Dosa Corner=[2, 5, 8, 11], Pizza Lane=[4, 7, 10]}
orders per restaurant : {Spice Hut=5, Dosa Corner=4, Pizza Lane=3}
delivered rev per day : {2026-11-28=84400, 2026-11-29=99200, 2026-11-30=140800}
average order per city : {Bengaluru=41057.142857142855, Mysuru=48460.0}
2026-11-28 {Dosa Corner=1, Spice Hut=2}
2026-11-29 {Dosa Corner=1, Pizza Lane=2, Spice Hut=1}
2026-11-30 {Dosa Corner=2, Pizza Lane=1, Spice Hut=2}What you see: Spice Hut had 5 orders, Dosa Corner 4 and Pizza Lane 3. Delivered revenue per day was 84,400, 99,200 and 140,800 paise, in date order because of TreeMap::new. The average order was about ₹410.57 in Bengaluru and ₹484.60 in Mysuru. The nested map shows two orders from Spice Hut on 28 November, and so on.
Why: One pass, one pipeline, no loops and no manual map handling. The downstream collector is the "what to do per bucket" part.
Loop
Check the map yourself.
Map<String, Long> m = new HashMap<>();
for (Order o : orders) {
m.merge(o.restaurant(), 1L, Long::sum);
}groupingBy
Name the key and the result.
Map<String, Long> m = orders.stream()
.collect(groupingBy(Order::restaurant,
counting()));The shift: The key function and the per-group action are named separately, so the code reads like the report it produces.
Land it groupingBy takes a key function and a downstream collector that says what to do with each bucket, and a map factory when I need sorted or ordered keys.
- "How do I get sorted keys, or keys in first-seen order?"
-
Pass a map factory as the middle argument.
groupingBy(Order::day, TreeMap::new, counting())gives keys in sorted order, which suits dates and names.LinkedHashMap::newgives keys in the order in which they first appeared in the stream, which is useful when the source is already sorted by something else.Without a factory you get a
HashMap, and its iteration order can change between runs and JDK versions. Never print or compare a plainHashMapin a test and expect a stable order.If you want the values sorted too, for example "top restaurants by revenue", you have to sort the entries in a second step:
sorting entries by valueruns offlinemap.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))A map keyed by group cannot be sorted by its values.
For deterministic output (reports, tests), always give a
TreeMaporLinkedHashMap. - "What about groupingBy on a parallel stream?"
-
It works, and it is safe, because each thread builds its own partial maps and the maps are merged at the end. Merging maps of lists is relatively expensive, so the speed-up is smaller than for a plain sum.
There is a variant for parallel streams,
groupingByConcurrent, that uses one sharedConcurrentMapand skips the merge. It is faster for large unordered work, but the list order within a group no longer follows the source order, and the downstream collector must be safe for concurrent use.The result of both is correct when the downstream collector is. The danger remains lambdas with side effects, as before.
Question 60 measured both on five million rows: the object-based parallel version was not faster than sequential at that size, so measure first.
- "How do I group by two things at once, like day and restaurant?"
-
Two ways. Nest the grouping:
nested groupingruns offlinegroupingBy(Order::day, groupingBy(Order::restaurant, counting()))This gives a
Map<String, Map<String, Long>>, as in the demo. It is natural for report tables where the outer key is the row and the inner key is the column.Or make a composite key: a record
DayRestaurant(String day, String restaurant)and this grouping:grouping by a composite keyruns offlinegroupingBy(o -> new DayRestaurant(o.day(), o.restaurant()), counting())You get a flat map with a single lookup key, which is easier to join with other data and has well-defined
equalsandhashCode, since records generate them.I choose nested maps for printing and the record key for lookups and for joining data from two sources.
Avoid composite string keys such as
day + "|" + restaurant: they work, and they rot as soon as a value contains the separator. - "When should I let the database do the grouping instead?"
-
When the data lives in a database, and especially when it is large.
SELECT restaurant, COUNT(*) FROM orders GROUP BY restaurantruns next to the data, uses indexes, and returns a handful of rows. Pulling every order into Java to group it moves a million rows over the network to produce twelve numbers.Use the stream collectors for data already in memory: results of several services, a cached list, a file, a test. Use SQL for data that is still in the database.
A middle path: run the query in SQL to get row-level data you need (filtered and limited), and use
groupingByfor the final presentation.Chapter E8 covers when to push aggregation to the database and how to check the query plan.
Q47 · Scenario. "toMap throws IllegalStateException: Duplicate key. Why, and how do you fix it?"
Reveal answer
Strong answer Collectors.toMap(keyFn, valueFn) builds a map with one entry per element, and it refuses duplicate keys. When two elements produce the same key and no rule says how to combine their values, it throws this:
IllegalStateException: Duplicate key asha (attempted merging values 1 and 1)The message names the key and the two values. A new data set with a repeated customer, or a repeated id from a join, is enough to cause it in production while all tests with unique sample data pass.
Fix 1: a merge function as the third argument: toMap(Order::customer, o -> 1, Integer::sum). When a key repeats, the function receives the old and new value and returns the combined one. Here it counts orders per customer.
Fix 2: a map supplier as the fourth argument when order or type matters: toMap(k, v, Integer::sum, LinkedHashMap::new) or TreeMap::new.
Fix 3: use groupingBy when you want to keep every value for a key (groupingBy(Order::customer, mapping(Order::id, toList()))), or when the downstream collector does the combining. For "count per key" and "sum per key", groupingBy with counting() or summingInt is also the more readable choice.
Two other traps. toMap throws a NullPointerException if a value is null (the collector's internals reject null values). And the default map is a HashMap with no order guarantee.
The decision: if duplicates are a data error, let it throw, so you notice. If they are normal, decide the rule, and write it as a merge function.
Picture it The failure with the exact message, then three fixes that each produce a different, correct answer.
The setup: Q47_ToMap.java maps customers to 1, which fails on the second order from asha. It then fixes it with a merge function, with a merge function plus LinkedHashMap, with a unique key (the order id), and with groupingBy. Finally it triggers the null-value NPE.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q47_ToMap {
public static void main(String[] args) {
try {
Map<String, Integer> bad = Data.ORDERS.stream().collect(toMap(Order::customer, o -> 1));
} catch (IllegalStateException e) { System.out.println(e.getMessage()); }
Map<String, Integer> count = Data.ORDERS.stream().collect(toMap(Order::customer, o -> 1, Integer::sum));
System.out.println("fix 1, merge function : " + new TreeMap<>(count));
Map<String, Integer> sorted = Data.ORDERS.stream()
.collect(toMap(Order::customer, Order::totalCents, Integer::sum, LinkedHashMap::new)); // 4th argument: map type
System.out.println("fix 2, keeps first-seen order: " + sorted);
Map<String, Integer> byId = Data.ORDERS.stream().collect(toMap(o -> "order-" + o.id(), Order::totalCents));
System.out.println("unique keys need no merge: " + byId.size() + " entries");
Map<String, List<Integer>> multi = Data.ORDERS.stream().collect(groupingBy(Order::customer, TreeMap::new, mapping(Order::id, toList())));
System.out.println("fix 3, groupingBy keeps every value: " + multi);
try { Data.ORDERS.stream().collect(toMap(Order::id, o -> o.status().equals("DELIVERED") ? "ok" : null)); }
catch (NullPointerException e) { System.out.println("toMap with a null value -> NullPointerException"); }
}
}Make the invisible visible: Run it.
Duplicate key asha (attempted merging values 1 and 1)
fix 1, merge function : {asha=4, kiran=2, meera=3, ravi=3}
fix 2, keeps first-seen order: {asha=197900, ravi=89500, meera=125500, kiran=116800}
unique keys need no merge: 12 entries
fix 3, groupingBy keeps every value: {asha=[1, 4, 8, 12], kiran=[5, 9], meera=[3, 7, 11], ravi=[2, 6, 10]}
toMap with a null value -> NullPointerExceptionWhat you see: The exception text is Duplicate key asha (attempted merging values 1 and 1). The merge function gave {asha=4, kiran=2, meera=3, ravi=3}. With the revenue version and LinkedHashMap, the customers come out in first-seen order with their totals. Order ids are unique, so that map needs no merge. groupingBy kept all ids per customer. The null value produced a NullPointerException.
Why: toMap has no default rule for two values with one key, and it prefers an error to silently losing data.
Crashes
No rule for duplicates.
Map<String, Integer> m = orders.stream()
.collect(toMap(Order::customer,
o -> 1));
// IllegalStateException: Duplicate keyMerge function
Say how to combine.
Map<String, Integer> m = orders.stream()
.collect(toMap(Order::customer,
o -> 1,
Integer::sum));The shift: The third argument says what to do when two values meet at one key.
Land it toMap fails on duplicate keys on purpose, and I fix it with a merge function, a map supplier for order, or groupingBy when I want to keep every value.
- "Is there a toMap that keeps the first or the last value?"
-
Yes, with a merge function that picks one.
(first, second) -> firstkeeps the value that arrived first, and(first, second) -> secondkeeps the latest. Write it explicitly so the rule is visible:toMap(Order::customer, Order::id, (a, b) -> b)gives the id of each customer's last order in stream order."First" and "last" depend on encounter order, so on a parallel unordered stream the answer may differ between runs. For a reliable "latest", sort or use
maxBywith a comparator insidegroupingBy:groupingBy(Order::customer, maxBy(comparing(Order::day))).A hidden danger: keeping "any" duplicate quietly can hide a data problem. Decide whether duplicates are expected before you write
(a, b) -> a. If they are not, let it throw.A comment next to the merge function that states why duplicates are expected is worth the line.
- "Why does toMap reject null values?"
-
The collector's internals use map operations (
merge, and a null check beforeputIfAbsent) that cannot represent a null value, becausemergetreats null as "no mapping". So the collector fails early with aNullPointerExceptioninstead. The stack trace points at the collector, not at the lambda that returned null, which makes it hard to read.The fix is to avoid null values: filter them out first, replace with a default (
Objects.requireNonNullElse), or useOptionalas the value if absence has meaning. Or collect withHashMap::putin acollect(HashMap::new, (m, o) -> m.put(...), HashMap::putAll), which allows nulls but gives up the safety.The same rejection applies to null keys in
groupingBy, which throwsNullPointerException: element cannot be mapped to a null key. Both are deliberate: collectors prefer a clear failure.When you see an NPE from
toMap, look at the value function first. - "Does toMap need a HashMap, or can it build other types?"
-
The four-argument form takes a
Supplierfor anyMap:TreeMap::newfor sorted keys,LinkedHashMap::newfor first-seen order,ConcurrentHashMap::newfor a map that other threads read while it fills, orEnumMapif the keys are enum values, which is fast and compact.There are also
toUnmodifiableMap(Java 10) for an immutable result, andtoConcurrentMapfor parallel streams. Both have the same duplicate-key rule.The default
HashMapis fine for lookups. The reason to choose another is almost always iteration order: reports and JSON output should be in a stable order, so useTreeMaporLinkedHashMap.A subtle point:
Map.copyOfandtoUnmodifiableMaphave a random iteration order that changes between JVM runs, so do not print them in tests. - "When is groupingBy a better answer than toMap?"
-
When keys repeat and you want something computed from all of the values of one key: count, sum, list, set, max.
groupingBy(key, downstream)expresses it directly, and the downstream collector is the combining rule. A merge function does the same only for two values at a time and is awkward for a list.When keys are unique by design (an id, an email),
toMapis the right tool and the exception is a useful alarm if the data is wrong.Examples: "orders per customer" is
groupingBy(..., counting()). "customer by id" istoMap(Customer::id, identity()). "latest order per customer" isgroupingBy(..., maxBy(...)), then map the optionals.If you find yourself writing a merge function that adds to a list, you wanted
groupingBy.
Q48. "partitioningBy versus groupingBy."
Reveal answer
Strong answer partitioningBy(predicate) splits elements into exactly two groups, keyed by true and false: the elements that pass the predicate and the ones that do not. groupingBy(function) splits them into any number of groups, keyed by whatever the function returns. Partitioning is the special case of grouping by a boolean, with extras.
Three differences matter in practice.
- Both keys always exist. A partition result always has a
trueentry and afalseentry, even when one side is empty (an empty list or zero).groupingByonly creates a bucket when some element falls into it, so a missing key means "no elements" andgetreturnsnull. - The map type is special. The result is a small internal map that only holds two keys and is fast to read. You cannot choose a different map type.
- Downstream collectors work the same.
partitioningBy(p, counting())counts both sides.partitioningBy(p, mapping(f, toList()))transforms before collecting.
Choose partitioningBy for a yes-or-no split where you will read both sides: valid and invalid records, delivered and not delivered, in stock and sold out. The always-present keys save you a null check. Choose groupingBy for more than two categories or when absent groups should stay absent.
A tempting mistake is to use groupingBy(o -> o.status().equals("DELIVERED")) for a two-way split. It works, but on an empty or one-sided input map.get(false) returns null and the next line throws a NullPointerException.
Picture it A delivered versus not-delivered split of the twelve orders, the same split on empty input with both collectors, and a three-way grouping for comparison.
The setup: Q48_Partition.java partitions orders into ids of delivered and other orders, repeats it on an empty input with partitioningBy and with groupingBy, counts big and small orders, and groups by status for three buckets.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q48_Partition {
public static void main(String[] args) {
Map<Boolean, List<Integer>> p = Data.ORDERS.stream()
.collect(partitioningBy(o -> o.status().equals("DELIVERED"), mapping(Order::id, toList())));
System.out.println("partitioningBy: " + p);
System.out.println(" false=" + p.get(false) + " true=" + p.get(true));
Map<Boolean, List<Integer>> none = Data.ORDERS.stream()
.filter(o -> o.id() > 100).collect(partitioningBy(o -> o.id() % 2 == 0, mapping(Order::id, toList())));
System.out.println("empty input still has both keys: " + none);
Map<Boolean, List<Integer>> g = Data.ORDERS.stream()
.filter(o -> o.id() > 100).collect(groupingBy(o -> o.id() % 2 == 0, mapping(Order::id, toList())));
System.out.println("groupingBy on empty input: " + g);
Map<Boolean, Long> counts = Data.ORDERS.stream().collect(partitioningBy(o -> o.totalCents() > 40000, counting()));
System.out.println("big vs small order counts: " + counts);
System.out.println("partition map type: " + p.getClass().getSimpleName());
Map<String, List<Integer>> multi = Data.ORDERS.stream().collect(groupingBy(o -> o.status(), TreeMap::new, mapping(Order::id, toList())));
System.out.println("groupingBy status (3 buckets): " + multi);
}
}Make the invisible visible: Run it.
partitioningBy: {false=[3, 7, 10, 12], true=[1, 2, 4, 5, 6, 8, 9, 11]}
false=[3, 7, 10, 12] true=[1, 2, 4, 5, 6, 8, 9, 11]
empty input still has both keys: {false=[], true=[]}
groupingBy on empty input: {}
big vs small order counts: {false=7, true=5}
partition map type: Partition
groupingBy status (3 buckets): {CANCELLED=[3, 10], DELIVERED=[1, 2, 4, 5, 6, 8, 9, 11], PREPARING=[7, 12]}What you see: The delivered orders (true) are 1, 2, 4, 5, 6, 8, 9, 11, and the others (false) are 3, 7, 10, 12. On empty input the partition still printed {false=[], true=[]}, while groupingBy printed {}. Big orders (above ₹400): 5, small: 7. Grouping by status gave three buckets: cancelled, delivered and preparing.
Why: A partition is defined to have both sides. A grouping only has the groups it found.
groupingBy
A missing key means null.
var m = orders.stream().collect(
groupingBy(o -> o.id() % 2 == 0));
m.get(true).size();
// NPE if no even idspartitioningBy
Both keys always there.
var m = orders.stream().collect(
partitioningBy(o -> o.id() % 2 == 0));
m.get(true).size();
// 0 when none, never nullThe shift: Because both keys are guaranteed, the lookup is safe even on empty data.
Land it partitioningBy splits into exactly two groups with both keys always present, and groupingBy makes as many groups as the key function finds, with absent groups simply missing.
- "Can I choose the map type or the list type for a partition?"
-
You cannot choose the map: the partition result is an internal two-entry map, and the collector has no map-factory argument. You can choose what goes into each side through the downstream collector.
partitioningBy(p, toSet())gives sets,partitioningBy(p, counting())gives counts, and this gives unmodifiable lists:partitioningBy with a downstream collectorruns offlinepartitioningBy(p, collectingAndThen(toList(), Collections::unmodifiableList))The default downstream is
toList(), which in practice yieldsArrayLists.If you really need a different map type (rare), use
groupingBywith a boolean classifier and aTreeMap::newfactory, and add your own default for a missing key.In practice the internal map is a perk: iteration order is always false then true, which makes printed output stable.
- "When would I use partitioningBy with a downstream collector?"
-
When you want a statistic for both sides in one pass.
partitioningBy(o -> o.totalCents() > 40000, counting())gives the number of big and small orders.partitioningBy(delivered, summingInt(Order::totalCents))gives revenue delivered against revenue still pending.It also pairs with
teeingoraveragingIntto compare the two sides: average order of repeat customers against new customers.Another example is validation:
partitioningBy(this::isValid)givesget(true)for rows to import andget(false)for rows to report, in a single pass over the file.The alternative, two
filtercalls, reads the source twice and needs a stream (or a list) for each. A partition is one traversal. - "Is partitioningBy faster than two filters?"
-
It avoids reading the source twice, which matters when the source is expensive to read (a file or a database cursor), and when the predicate is expensive. For an in-memory list of a few thousand elements, the difference is below the noise. Clarity is the reason to choose it: the single call shows that the two outputs are complementary.
Two filters with a stored predicate and its negation (
filter(p),filter(p.negate())) are easy to get out of sync if someone edits one side.On a one-pass-only source, a stream cannot be consumed twice (question 38), so partitioning is the only way to get both sides from one stream.
So: partition when you need both sides, filter when you need one.
- "What are the traps with partitioningBy?"
-
The first is thinking the result has special laziness: it does not. The collector reads the whole stream, builds both lists and returns. A partition of a large stream stores all of it in memory.
The second is forgetting that elements for which the predicate throws or returns null (for a
Booleanpredicate) cause an error. The predicate must return a plainboolean.The third is using
partitioningByfor a three-way split by nesting:partitioningBy(a, partitioningBy(b))gives four buckets, not three, because the inner partition applies to both sides. If you need three states, use an enum andgroupingBy.The fourth is relying on the list inside being mutable. It is today, and the Javadoc does not promise it.
Q49. "teeing (12): compute the minimum and maximum in one pass."
Reveal answer
Strong answer Collectors.teeing(collector1, collector2, merger) runs two collectors on the same stream in one pass and combines their two results with a function. The name comes from the tee fitting in plumbing: one flow, two outputs. It was added in Java 12.
The problem it solves: you want two answers from one stream, and a stream can only be consumed once (question 38). Before Java 12 you had three poor choices: stream the list twice, build a helper object with a custom collector, or collect into a list and process it twice.
The example:
teeing(minBy(Integer::compare), maxBy(Integer::compare),
(lo, hi) -> new Range(lo.get(), hi.get()))Both minBy and maxBy return an Optional, because an empty stream has no minimum, and the merger unwraps them. The result is a Range record with the smallest and largest total.
Another: count and sum together, so that you can divide them.
teeing(counting(), summingInt(f), (n, sum) -> sum / (double) n)This gives an average that you control, with the empty-stream case under your control as well.
Both collectors can be any collector, including groupingBy, so each branch can build a complex result. For plain primitives, summaryStatistics() on an IntStream already gives count, sum, min, average and max in one pass.
Use teeing when two different results are needed and no built-in summary fits.
Picture it Minimum and maximum of the twelve order totals, then a count-and-sum average, with a proof that the source was read once.
The setup: Q49_Teeing.java computes a Range and a Stats record using teeing. It compares with two separate streams, and counts how many elements the pipeline reads with a peek counter. Finally it prints the built-in summaryStatistics().
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q49_Teeing {
record Range(int min, int max) {}
record Stats(long count, int sum, double avg) {}
public static void main(String[] args) {
Range r = Data.ORDERS.stream().map(Order::totalCents)
.collect(teeing(minBy(Integer::compare), maxBy(Integer::compare),
(lo, hi) -> new Range(lo.get(), hi.get())));
System.out.println(r);
Stats s = Data.ORDERS.stream().collect(teeing(counting(), summingInt(Order::totalCents),
(n, sum) -> new Stats(n, sum, sum / (double) n)));
System.out.println(s);
// the same two answers the old way: two passes over the data (and a stream cannot be re-used)
int lo = Data.ORDERS.stream().mapToInt(Order::totalCents).min().getAsInt();
int hi = Data.ORDERS.stream().mapToInt(Order::totalCents).max().getAsInt();
System.out.println("two passes: " + new Range(lo, hi));
// one pass, proven: count how many times the source is read
int[] reads = {0};
Data.ORDERS.stream().peek(o -> reads[0]++).collect(teeing(counting(), summingInt(Order::totalCents), (n, t) -> n + "/" + t));
System.out.println("elements read by teeing: " + reads[0] + " (12 orders, one pass)");
var stats = Data.ORDERS.stream().mapToInt(Order::totalCents).summaryStatistics();
System.out.println(stats);
}
}Make the invisible visible: Run it.
Range[min=21900, max=89400]
Stats[count=12, sum=529700, avg=44141.666666666664]
two passes: Range[min=21900, max=89400]
elements read by teeing: 12 (12 orders, one pass)
IntSummaryStatistics{count=12, sum=529700, min=21900, average=44141.666667, max=89400}What you see: The range was 21,900 to 89,400. The stats record had count 12, sum 529,700 and average 44,141.67. The two-stream version gave the same range but needed two passes. The peek counter read 12 elements, once for each order, although two collectors ran. The built-in statistics agree with all of it.
Why: teeing passes each element to both collectors, so the source is traversed once whatever the number of collectors.
Two passes
The stream is rebuilt.
int lo = orders.stream()
.mapToInt(Order::totalCents)
.min().getAsInt();
int hi = orders.stream()
.mapToInt(Order::totalCents)
.max().getAsInt();teeing
One pass, one merge.
var r = orders.stream().collect(teeing(
minBy(comparingInt(Order::totalCents)),
maxBy(comparingInt(Order::totalCents)),
(lo, hi) -> new Range(lo.get(), hi.get())));The shift: Each element is offered to both collectors, and the merger combines their finished results.
Land it teeing runs two collectors in one pass over the stream and merges their results, which is what I use when a stream cannot be read twice.
- "Why not just collect to a list and process it twice?"
-
You can, and for a few hundred elements it is fine, and often the clearest. The cost is memory (the whole list is held) and a second traversal. For a stream that is large, infinite or comes from a file, a list is the thing you are trying to avoid.
The one-pass approach also keeps results consistent: both answers come from exactly the same elements. With two passes over a mutable source, the data could change between them.
If the source is already a collection in memory,
list.stream()twice costs almost nothing. I then choose by readability. Twominandmaxlines are easy to understand, andteeingshines when the branches are bigger collectors.The real advantage appears with streams that cannot be replayed: lines from a file, rows from a cursor and events from a queue.
- "Can I combine more than two collectors?"
-
Nest
teeinginsideteeing. The merger of the outer call takes the result of the inner one:nested teeingruns offlineteeing(counting(), teeing(minBy(c), maxBy(c), Range::of), (n, range) -> ...)It gets hard to read at three levels, so I would define a record and a small custom collector instead (question 53).
For statistics, use
summarizingInt,summarizingLongorsummarizingDouble, which already hold count, sum, min, max and average, and which can be used as a downstream collector ingroupingBy.The nested form is correct and safe. The only cost is clarity. A comment or a named helper method for the combined collector makes it readable.
If you need five numbers from one stream, a custom
Collectorwith a small accumulator class is the cleaner design. - "What happens with teeing on an empty stream?"
-
Each branch does what it does on an empty stream.
minByandmaxByreturn empty Optionals,counting()returns 0,summingIntreturns 0 andaveragingIntreturns 0.0. The merger still runs, receiving those values, so a merger that callslo.get()on an empty Optional throwsNoSuchElementException.Plan for it: use
orElse(...)in the merger, or make the merger return an Optional or a record with a flag.It is easy to miss in tests, because test data usually has elements. An empty-input test is cheap and catches it: run the pipeline on
Stream.empty()and check the result.The same applies to every collector that returns an Optional, including
reduce,maxByandminBy. - "Does teeing run the collectors in parallel?"
-
It runs both collectors on every element, in the same thread that processes that element. It does not give each collector its own thread. If the stream is parallel, the stream itself splits across threads, and each thread keeps a pair of accumulators, one for each collector. The pairs merge at the end, using each collector's combiner.
So
teeingis as parallel-safe as the two collectors in it. Built-in ones are. A custom collector needs a correct combiner (question 53).Do not expect speed from
teeingitself. Its benefit is saving a traversal, and keeping the code in one place.If the two computations are slow and independent, such as two service calls, parallelism belongs in the stream or an executor, not in
teeing.
Q50. "How do you get the top three items per category with streams?"
Reveal answer
Strong answer The idea has three parts: group by category, rank inside each group, keep three. In QuickBite terms, the category is the restaurant and the ranking is total quantity sold per item.
- Flatten: an order has several lines, so first
flatMaporders into rows of restaurant and line. AMap.entry(restaurant, line)or a small record serves as the row. - Total per item: group by restaurant, then by item name, and sum the quantities:
groupingBy(restaurant, groupingBy(item, summingInt(qty))). You now have a map of maps. - Rank and cut: for each restaurant, sort the item totals by quantity descending (with a tie-break on name so that the result is deterministic), and keep the first three with
limit(3).
The final cut can be a second loop over the grouped map, as in the first half of the demo, or it can be done inside the same pipeline with collectingAndThen as the downstream collector of the outer grouping, which turns each inner map into the top-three list in the same expression.
Always add a tie-breaker. Without it, items with equal quantity come out in a hash-dependent order and the top three can change between runs (in the demo, Pizza Lane has three items that all sold 2).
For huge data sets, sorting each group fully is wasteful. A bounded heap per group (a custom collector with a PriorityQueue of size three) keeps memory small, as question 53 shows. For data that lives in a database, ROW_NUMBER() OVER (PARTITION BY ...) does it better.
Picture it Item quantities per restaurant, then the top three per restaurant, built two ways that give the same answer.
The setup: Q50_TopN.java builds the nested quantity map, then takes the top three per restaurant with a second loop. It repeats the job inside one pipeline with collectingAndThen, where each result is a small Sold record.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q50_TopN {
record Sold(String item, int qty) {}
public static void main(String[] args) {
// step 1: flatten orders into (restaurant, item, qty) rows and add up per item
Map<String, Map<String, Integer>> qtyByItem = Data.ORDERS.stream()
.flatMap(o -> o.lines().stream().map(l -> Map.entry(o.restaurant(), l)))
.collect(groupingBy(Map.Entry::getKey, TreeMap::new,
groupingBy(e -> e.getValue().item(), TreeMap::new, summingInt(e -> e.getValue().qty()))));
System.out.println(qtyByItem);
// step 2: per restaurant, sort the items by quantity and keep the top 3
Map<String, List<String>> top3 = new TreeMap<>();
qtyByItem.forEach((rest, items) -> top3.put(rest, items.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
.limit(3).map(e -> e.getKey() + "x" + e.getValue()).toList()));
System.out.println(top3);
// the same in ONE pipeline: group, then collectingAndThen on every bucket
Map<String, List<Sold>> oneShot = Data.ORDERS.stream()
.flatMap(o -> o.lines().stream().map(l -> Map.entry(o.restaurant(), new Sold(l.item(), l.qty()))))
.collect(groupingBy(Map.Entry::getKey, TreeMap::new,
collectingAndThen(
groupingBy(e -> e.getValue().item(), summingInt(e -> e.getValue().qty())),
m -> m.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
.limit(3).map(e -> new Sold(e.getKey(), e.getValue())).toList())));
oneShot.forEach((r, l) -> System.out.println(r + " -> " + l));
}
}Make the invisible visible: Run it.
{Dosa Corner={filter coffee=4, idli=4, masala dosa=5, rava dosa=2}, Pizza Lane={coke=2, farmhouse=2, margherita=2}, Spice Hut={biryani=7, paneer tikka=3, raita=4}}
{Dosa Corner=[masala dosax5, filter coffeex4, idlix4], Pizza Lane=[cokex2, farmhousex2, margheritax2], Spice Hut=[biryanix7, raitax4, paneer tikkax3]}
Dosa Corner -> [Sold[item=masala dosa, qty=5], Sold[item=filter coffee, qty=4], Sold[item=idli, qty=4]]
Pizza Lane -> [Sold[item=coke, qty=2], Sold[item=farmhouse, qty=2], Sold[item=margherita, qty=2]]
Spice Hut -> [Sold[item=biryani, qty=7], Sold[item=raita, qty=4], Sold[item=paneer tikka, qty=3]]What you see: Spice Hut sold 7 biryani, 4 raita and 3 paneer tikka. Dosa Corner sold 5 masala dosa, then 4 filter coffee and 4 idli (tie broken by name). Pizza Lane has only three items, all with quantity 2. The one-pipeline version prints the same three lists as records.
Why: The tie-break thenComparing(Map.Entry.comparingByKey()) keeps filter coffee ahead of idli, so the answer is the same on every run.
Loop
Sort each group by hand.
for (var e : byRestaurant.entrySet()) {
var items = new ArrayList<>(
e.getValue().entrySet());
items.sort(byQtyThenName);
top.put(e.getKey(), items.subList(0, 3));
}Pipeline
collectingAndThen does it.
groupingBy(Order::restaurant,
collectingAndThen(
groupingBy(item, summingInt(qty)),
m -> topThree(m)));
// topThree sorts and limitsThe shift: The "keep three" step moves into the collector, so the whole report is a single expression.
Land it I flatten the orders, group by category and item to sum quantities, then sort each group with a tie-break and keep three, using collectingAndThen when it should be one expression.
- "Why do I need a tie-breaker?"
-
Because sorting by quantity alone leaves ties unordered. Items that share a quantity come out in whatever order the map iterates, and for a
HashMapthat order depends on the hash codes and the JVM version. The top three can then change between runs or after an upgrade, which is awful for a report or a test.The stream's
sortedis stable for ordered streams, so equal elements keep their input order, but the input order from aHashMapis itself arbitrary. Using aTreeMapfor the inner grouping or a second comparator fixes it.The demo uses
thenComparing(Map.Entry.comparingByKey())for this. In a test with expected values, the tie-breaker is what makes the assertion stable.The same applies to any "top N": define the order completely, including ties.
- "How would this look in SQL, and when is that better?"
-
With a window function:
top 3 per restaurant in SQLruns offlineSELECT * FROM ( SELECT restaurant, item, SUM(qty) AS total, ROW_NUMBER() OVER (PARTITION BY restaurant ORDER BY SUM(qty) DESC, item) AS rn FROM order_lines GROUP BY restaurant, item ) t WHERE rn <= 3The database does the ranking with an index and returns only the top rows.
SQL is better when the data is in a database and large. The stream version is right when the data is already in memory, comes from several sources, or the result needs logic that is awkward in SQL.
The cost of the stream version at scale is that every row has to be loaded, grouped and sorted in Java, which takes memory and network time.
Chapter E8 covers window functions and their query plans.
- "Can I do this without sorting whole groups?"
-
Yes: a bounded priority queue per group. Keep a min-heap of size three. For each element, add it, and if the heap has more than three, remove the smallest. At the end the heap holds the three largest. Memory is three items per group, and the work is N times log 3, which is effectively linear.
Write it as a custom
Collectorand use it as the downstream ofgroupingBy. Question 53 builds a top-two collector this way. The result is the same as sort-and-limit, and it scales to millions of elements per group.Remember that
sorted().limit(3)does not do this for you: it sorts everything first (question 37 measured it running out of memory).For small groups, sort-and-limit is simpler. Choose the heap when groups are large.
- "What if I need ranks with ties, like two items in joint third place?"
-
Then "top three" is ambiguous, and you need to decide the rule: strictly three items (cut ties arbitrarily or by name), or all items whose quantity is at least the third-highest quantity (which may return more than three).
For the second rule, find the third-highest distinct quantity, then
filterthe group for quantities at or above it. With sorted distinct quantities, this gets the cut-off:the cut-off quantityruns offlineqtys.stream().distinct().sorted(reverseOrder()).skip(2).findFirst()Write the rule down in the method name or comment, since it changes what is shown to customers: "top 3 dishes" with four dishes listed raises questions.
SQL's
RANK()andDENSE_RANK()are the window functions for "with ties", andROW_NUMBER()is the strict cut.
Q51. "The mapping, filtering (9), flatMapping (9) and joining collectors."
Reveal answer
Strong answer These four are downstream collectors, the ones you put inside groupingBy or partitioningBy to shape each bucket. They are the collector versions of map, filter and flatMap, plus string joining.
mapping(function, downstream) transforms each element first, then hands it to the downstream collector. groupingBy(Order::city, mapping(Order::customer, toSet())) gives the set of customer names per city, not the set of orders.
filtering(predicate, downstream) (Java 9) drops elements inside each bucket. It is different from a filter before the grouping: a stream filter removes elements first, and groups that lose every element vanish from the map. filtering keeps the group and shows a zero or an empty collection. That is the difference for reports that need every restaurant listed.
flatMapping(function, downstream) (Java 9) maps each element to a stream and flattens the results inside the bucket: all item names per restaurant from orders that have several lines.
joining() concatenates strings. Three forms: joining(), joining(", ") and joining(", ", "[", "]") with prefix and suffix. It works only on a stream of CharSequence, so map to strings first.
Related: collectingAndThen(downstream, finisher) post-processes the result (for example wraps it in an unmodifiable collection), and summarizingInt gives count, sum, min, average and max for a bucket.
A good rule: if you would write map, filter or flatMap on the elements of each group after grouping, use the collector with the same name instead.
Picture it All four on the QuickBite orders. The filtering example is shown next to its stream-filter twin so the difference is visible.
The setup: Q51_Collectors.java groups customers by city with mapping, counts large orders per restaurant by filtering first and by filtering, flattens item names per restaurant, joins customer names three ways, and uses collectingAndThen, summarizingInt and maxBy.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q51_Collectors {
public static void main(String[] args) {
// mapping: transform each element BEFORE the downstream collector sees it
TreeMap<String, TreeSet<String>> who = Data.ORDERS.stream()
.collect(groupingBy(Order::city, TreeMap::new, mapping(Order::customer, toCollection(TreeSet::new))));
System.out.println("mapping : " + who);
// filtering (9): drop elements INSIDE each bucket, so empty buckets survive
System.out.println("filter first : " + Data.ORDERS.stream().filter(o -> o.totalCents() > 60000)
.collect(groupingBy(Order::restaurant, TreeMap::new, counting())));
System.out.println("filtering : " + Data.ORDERS.stream()
.collect(groupingBy(Order::restaurant, TreeMap::new, filtering(o -> o.totalCents() > 60000, counting()))));
// flatMapping (9): one element -> many, inside each bucket
System.out.println("flatMapping : " + Data.ORDERS.stream()
.collect(groupingBy(Order::restaurant, TreeMap::new, flatMapping(o -> o.lines().stream().map(Line::item), toCollection(TreeSet::new)))));
// joining: Strings only (map first), three overloads
System.out.println(Data.ORDERS.stream().limit(4).map(Order::customer).collect(joining()));
System.out.println(Data.ORDERS.stream().limit(4).map(Order::customer).collect(joining(", ")));
System.out.println(Data.ORDERS.stream().limit(4).map(Order::customer).collect(joining(", ", "[", "]")));
// collectingAndThen: finish with a function (here: wrap as unmodifiable)
List<Integer> ids = Data.ORDERS.stream().map(Order::id).limit(3).collect(collectingAndThen(toList(), Collections::unmodifiableList));
try { ids.add(99); } catch (UnsupportedOperationException e) { System.out.println("collectingAndThen -> unmodifiable " + ids); }
// summarizing: count, sum, min, avg, max in one go
System.out.println(Data.ORDERS.stream().collect(summarizingInt(Order::totalCents)));
// reducing and minBy, maxBy
System.out.println(Data.ORDERS.stream().collect(groupingBy(Order::restaurant, TreeMap::new,
maxBy(Comparator.comparingInt(Order::totalCents)))).values().stream().map(o -> o.get().id()).toList());
}
}Make the invisible visible: Run it.
mapping : {Bengaluru=[asha, ravi], Mysuru=[kiran, meera]}
filter first : {Pizza Lane=1, Spice Hut=2}
filtering : {Dosa Corner=0, Pizza Lane=1, Spice Hut=2}
flatMapping : {Dosa Corner=[filter coffee, idli, masala dosa, rava dosa], Pizza Lane=[coke, farmhouse, margherita], Spice Hut=[biryani, paneer tikka, raita]}
asharavimeeraasha
asha, ravi, meera, asha
[asha, ravi, meera, asha]
collectingAndThen -> unmodifiable [1, 2, 3]
IntSummaryStatistics{count=12, sum=529700, min=21900, average=44141.666667, max=89400}
[2, 7, 9]What you see: Bengaluru's customers are asha and ravi, Mysuru's are kiran and meera. Counting orders above ₹600 with a stream filter gives only the two restaurants that have such orders, while filtering inside the grouping also shows Dosa Corner=0. flatMapping listed every item per restaurant. The three joining forms show the delimiter, prefix and suffix.
Why: The collector version runs inside each bucket, so an empty bucket can still appear with an empty answer. A stream filter in front of the grouping makes the group disappear.
filter first
The group disappears.
orders.stream()
.filter(o -> o.totalCents() > 60000)
.collect(groupingBy(Order::restaurant,
counting()));
// {Pizza Lane=1, Spice Hut=2}filtering
The group stays with zero.
orders.stream()
.collect(groupingBy(Order::restaurant,
filtering(o -> o.totalCents() > 60000,
counting())));
// {Dosa Corner=0, Pizza Lane=1, Spice Hut=2}The shift: Filtering inside the collector keeps every key and counts only the matches within each.
Land it mapping, filtering and flatMapping are map, filter and flatMap applied inside each group, and joining builds a string, with filtering the one that keeps empty groups visible.
- "Why would I use mapping instead of a map before grouping?"
-
Because the grouping key often needs the whole element while the result needs only one field.
groupingBy(Order::city, mapping(Order::customer, toSet()))groups by something on the order and keeps just the customer. If you appliedmap(Order::customer)first, the city would be gone and you could not group by it.It keeps the key function and the value function in one expression, which reads like a SQL
SELECT city, ARRAY_AGG(customer) GROUP BY city.The same holds for
toMap, where the key and value functions both see the full element, and forteeing, where each branch sees the full element and can map it as it likes.A rule I use: a transformation that changes what the element is goes before grouping only if the key does not need the old element. Otherwise put it inside as
mapping. - "When is filtering inside a group different from filtering before it?"
-
When the empty groups matter. A report of "large orders per restaurant" that omits a restaurant with none looks like a bug to a business reader: they want to see "Dosa Corner: 0". Filtering before grouping removes the whole group, and filtering inside keeps it.
It also matters when several statistics share one grouping: you may want the total count per restaurant and the count of large orders per restaurant from the same pass. With
teeingor a custom collector, you can have one downstream withfilteringand one without.If you do not care about empty groups, a plain stream
filteris simpler and slightly faster, because fewer elements reach the collector.Remember that a restaurant with no orders at all will not appear either way, because a group exists only if some element had that key. To list known restaurants, start from the list of restaurants and look up counts, or use
getOrDefault(key, 0L). - "What is flatMapping for, given that I can flatMap the stream first?"
-
The same reason as
mapping: the grouping key must be computed from the element before it is flattened.flatMapping inside groupingByruns offlinegroupingBy(Order::restaurant, flatMapping(o -> o.lines().stream().map(Line::item), toSet()))This groups orders by restaurant but collects the items of all their lines. If you flatMapped the orders into lines first, you would have lost the restaurant (unless you build a pair).
It is therefore the right tool for "per group, collect the many parts of each element". In the demo, the set of distinct item names per restaurant.
When the grouping key is available on the flattened element, flatMapping adds nothing and a
flatMapin front is simpler.It was added in Java 9 together with
filtering. Before that, you needed a custom collector or a two-step process. - "What are the traps with joining?"
-
joiningaccepts onlyCharSequence, so a stream of numbers or objects needsmap(String::valueOf)or amapto a field first. The compile error mentionsCharSequence, and the fix is the map.It joins nulls as the text "null" (the elements are turned into text by
append), which hides missing data. Filter out nulls first if that matters.It gives an empty string for an empty stream, and with prefix and suffix it gives only prefix and suffix:
joining(",", "[", "]")on nothing yields[], which is convenient for JSON-like output.For very large outputs, one big string is held in memory. Stream to a writer instead (
forEachon aPrintWriter) for files and responses.For a plain list,
String.join(", ", list)is shorter.joiningis for pipelines.
Q52. "Which collectors return unmodifiable results, and since when?"
Reveal answer
Strong answer Four routes give an unmodifiable result, each from a different release.
Collectors.toUnmodifiableList(),toUnmodifiableSet(),toUnmodifiableMap()(Java 10). Immutable results, with no nulls allowed.toUnmodifiableMapthrows on duplicate keys liketoMap, andtoUnmodifiableSetsilently ignores duplicate elements.Stream.toList()(Java 16). An unmodifiable list, nulls allowed. It is a stream method, not a collector.collectingAndThen(downstream, Collections::unmodifiableMap)(any version). Wrap any result in a read-only view. It works forgroupingByandpartitioningByresults, which have no unmodifiable variants.- Copy factories
List.copyOf,Set.copyOf,Map.copyOf(Java 10) applied to a collected result.
The collectors that give you no promise, though in practice they are mutable: toList(), toSet(), toMap(), groupingBy(), partitioningBy(). The Javadoc says there are no guarantees on the type, mutability or thread safety of what is returned. That means you may not rely on changing the result, and you may not rely on it being unmodifiable either.
Note on groupingBy: the map is mutable in practice, and so are the lists inside. To make everything unmodifiable, give the downstream toUnmodifiableList() and wrap the outer map with collectingAndThen.
Use unmodifiable results for anything you return from a method or store in a field, so callers cannot change your data. Use toCollection(ArrayList::new) when you want a mutable list on purpose.
Picture it Every collector family probed with an add or put, with compile proofs that the Java 10 and Java 16 methods did not exist before their release.
The setup: Q52_Unmodifiable.java tries to change the result of each collector and prints "mutable" or "unmodifiable". Q52_Proof.java uses toUnmodifiableList (10) and Stream.toList() (16) and is compiled with releases 9, 10 and 16.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q52_Unmodifiable {
static String tryAdd(Collection<String> c) {
try { c.add("x"); return "mutable"; } catch (UnsupportedOperationException e) { return "unmodifiable"; }
}
public static void main(String[] args) {
System.out.println("toList() -> " + tryAdd(Stream.of("a").toList())); // 16
System.out.println("toUnmodifiableList() -> " + tryAdd(Stream.of("a").collect(toUnmodifiableList()))); // 10
System.out.println("toUnmodifiableSet() -> " + tryAdd(Stream.of("a").collect(toUnmodifiableSet()))); // 10
System.out.println("toUnmodifiableMap() -> " + tryAddMap(Stream.of("a").collect(toUnmodifiableMap(x -> x, x -> 1)))); // 10
System.out.println("collect(toList()) -> " + tryAdd(Stream.of("a").collect(toList()))); // "no guarantee"
System.out.println("collect(toSet()) -> " + tryAdd(Stream.of("a").collect(toSet())));
System.out.println("collect(toMap(..)) -> " + tryAddMap(Stream.of("a").collect(toMap(x -> x, x -> 1))));
System.out.println("collect(groupingBy(..)) -> " + tryAddMap(Stream.of("a").collect(groupingBy(x -> x, counting()))));
var m = Stream.of("a").collect(collectingAndThen(groupingBy(x -> x, counting()), Collections::unmodifiableMap));
System.out.println("groupingBy + collectingAndThen(unmodifiableMap) -> " + tryAddMap(m));
try { Stream.of("a", "a").collect(toUnmodifiableSet()); System.out.println("toUnmodifiableSet keeps duplicates out silently"); }
catch (IllegalArgumentException e) { System.out.println(e); }
try { Stream.of("a", "a").collect(toUnmodifiableMap(x -> x, x -> 1)); } catch (IllegalStateException e) { System.out.println("toUnmodifiableMap duplicate: " + e.getMessage()); }
}
static String tryAddMap(Map<String, ?> m) {
try { m.put("zzz", null); return "mutable"; } catch (UnsupportedOperationException e) { return "unmodifiable"; } catch (NullPointerException e) { return "unmodifiable (NPE on null)"; }
}
}Make the invisible visible: Compile proofs, then the run.
$ javac --release 9 Q52_Proof.java
Q52_Proof.java:5: error: cannot find symbol
Object a = Stream.of("x").collect(Collectors.toUnmodifiableList()); // Java 10
^
symbol: method toUnmodifiableList()
location: class Collectors
... (1 more errors trimmed)
$ javac --release 10 Q52_Proof.java
Q52_Proof.java:6: error: cannot find symbol
Object b = Stream.of("x").toList(); // Java 16
^
symbol: method toList()
location: interface Stream<String>
$ javac --release 15 Q52_Proof.java
Q52_Proof.java:6: error: cannot find symbol
Object b = Stream.of("x").toList(); // Java 16
^
symbol: method toList()
location: interface Stream<String>
$ javac --release 16 Q52_Proof.java
(compiles)
toList() -> unmodifiable
toUnmodifiableList() -> unmodifiable
toUnmodifiableSet() -> unmodifiable
toUnmodifiableMap() -> unmodifiable
collect(toList()) -> mutable
collect(toSet()) -> mutable
collect(toMap(..)) -> mutable
collect(groupingBy(..)) -> mutable
groupingBy + collectingAndThen(unmodifiableMap) -> unmodifiable
toUnmodifiableSet keeps duplicates out silently
toUnmodifiableMap duplicate: Duplicate key a (attempted merging values 1 and 1)What you see: Release 9 cannot find toUnmodifiableList. Release 10 has it, but then stops at Stream.toList(), which release 16 finally supplies. In the run, toList(), the three toUnmodifiable... collectors and the wrapped groupingBy are unmodifiable, and the plain collect(toList()), toSet(), toMap() and groupingBy() are mutable. toUnmodifiableMap reports duplicates as Duplicate key a (attempted merging values 1 and 1).
Why: The old collectors predate the idea of immutable collections, and their Javadoc never promised mutability. They are mutable by implementation, not by contract.
Unspecified
Mutable today, no promise.
Map<String, Long> m = orders.stream()
.collect(groupingBy(Order::city,
counting()));
m.put("x", 0L); // works, by accidentWrapped
Read-only on purpose.
Map<String, Long> m = orders.stream()
.collect(collectingAndThen(
groupingBy(Order::city, counting()),
Collections::unmodifiableMap));The shift: The wrapper turns an accidental property into a stated one that callers can rely on.
Land it The Java 10 toUnmodifiable collectors and Java 16 Stream.toList give unmodifiable results, and for groupingBy or partitioningBy I wrap with collectingAndThen.
- "Why do the unmodifiable collectors reject nulls?"
-
They produce the same family as
List.of,Set.ofandMap.of, the immutable collections of Java 9, which were designed to reject null: it keeps their behaviour simple and uniform (no special cases incontainsorequals) and finds null mistakes early. The failure message points at the stream pipeline that produced the null.Stream.toList()was designed later with a different goal: replacecollect(toList())without breaking the many callers that had nulls in their lists. So it allows them.When your data may contain nulls, you have to choose: filter them out first, replace them with a value, or use
toList()ortoCollection.Know the three behaviours:
List.ofandtoUnmodifiable*reject nulls,Stream.toList()andCollections.unmodifiableList(new ArrayList<>(...))allow them. - "How do I make a nested result, like a map of lists, fully unmodifiable?"
-
Make each level unmodifiable. The inner lists:
groupingBy(key, toUnmodifiableList())(ormapping(f, toUnmodifiableList())). The outer map: wrap withcollectingAndThen(groupingBy(...), Map::copyOf)orCollections::unmodifiableMap.Map.copyOfgives a truly immutable map with a random iteration order.Collections.unmodifiableMapis a read-only view of the original map, which keeps its order if it was aTreeMaporLinkedHashMapbut is not frozen if someone else holds the source.In the pipeline there is no one else holding the source, because the collector created it. So the wrapper is safe, and a
TreeMapwrapped this way keeps a sorted view.The elements themselves must be immutable for the whole structure to be. Records of immutable values are ideal.
- "Is it wrong to rely on collect(toList()) being mutable?"
-
It works today in every JDK, and the Javadoc explicitly says it makes no promise, so it is a hidden coupling that a future version could break. In practice the JDK team is unlikely to change it, because so much code depends on it, but a new JDK is allowed to.
The safe style is to state your intent. Want mutable?
collect(Collectors.toCollection(ArrayList::new)). Want unmodifiable?toList()ortoUnmodifiableList(). Do not care? Still pick one, because the next reader will.For existing code that works, I do not rewrite it all. I fix it when I touch it, and I never write new code that depends on the unspecified behaviour.
A static-analysis rule that flags
collect(toList())followed by a modification can catch these couplings. - "What is the difference between an unmodifiable view and an immutable copy again?"
-
A view (
Collections.unmodifiableList) wraps another collection and refuses writes through itself, but shows the source's changes. A copy (List.copyOf,toUnmodifiableList) has its own storage that nobody can change.For collector results, the distinction is mostly academic: the collector creates the list and gives it to you, with no other holder. So
collectingAndThen(toList(), Collections::unmodifiableList)andtoUnmodifiableList()behave the same for the caller, apart from null handling, because nobody else can touch the underlyingArrayList.The difference matters when you wrap a collection that someone else still owns, as in question 12's
viewexample.So use the copy form when starting from an existing collection, and either form for a fresh collector result.
Q53 · Design. "When is writing a custom Collector worth it? Write one."
Reveal answer
Strong answer Rarely, but sometimes. First check the built-in options. groupingBy, teeing, summarizingInt, reducing, mapping and the gatherers of Java 24 cover most needs.
Write a custom collector when: you need a result that none of them gives (a domain summary such as "count, min, max and average of order totals" for reuse); you want a bounded structure such as a top-N heap that avoids storing everything; you want a reusable named unit that several pipelines share; or you need a specialised container (a Bloom filter, a histogram).
A collector has four functions, plus optional characteristics:
- Supplier: creates an empty container (one per thread in parallel).
- Accumulator: folds one element into a container.
- Combiner: merges two containers into one (used when parallel; it must be correct even if you never run in parallel).
- Finisher: turns the container into the final result. If the container is the result, say
IDENTITY_FINISH.
Build it with this call:
Collector.of(supplier, accumulator, combiner, [finisher,] characteristics...)The accumulator changes its container, which is safe because each thread has its own. Never touch state outside the container.
The demo writes a Summary collector for QuickBite orders. The honest comment: IntSummaryStatistics already does count, sum, min, average and max for ints, so the demo's custom version is only worth it if it summarises something richer than a single int. For the top-N case it is genuinely better than the built-ins.
Test it three ways: sequential, parallel, and on an empty stream.
Picture it An order summary collector, run sequentially, in parallel and per city, compared with the built-in statistics. Then a bounded top-two collector that never holds more than two orders.
The setup: Q53_Collector.java has a Summary container with accept and merge, a Collector.of(...) factory around it, and a second collector that keeps the two most expensive orders in a PriorityQueue of size two.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Q53_Collector {
// the result type: mutable while collecting, we only read it at the end
static final class Summary {
long count; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; long sum;
void accept(int v) { count++; sum += v; min = Math.min(min, v); max = Math.max(max, v); }
Summary merge(Summary o) { count += o.count; sum += o.sum; min = Math.min(min, o.min); max = Math.max(max, o.max); return this; }
@Override public String toString() { return "count=%d min=%d max=%d avg=%.1f".formatted(count, min, max, count == 0 ? 0.0 : sum / (double) count); }
}
static Collector<Order, Summary, Summary> orderSummary() {
return Collector.of(
Summary::new, // supplier: one empty container per thread
(s, o) -> s.accept(o.totalCents()), // accumulator: fold one element in
Summary::merge, // combiner: join two containers (parallel)
Collector.Characteristics.IDENTITY_FINISH); // finisher not needed
}
public static void main(String[] args) {
System.out.println("custom : " + Data.ORDERS.stream().collect(orderSummary()));
System.out.println("parallel : " + Data.ORDERS.parallelStream().collect(orderSummary()));
System.out.println("per city : " + new TreeMap<>(Data.ORDERS.stream().collect(Collectors.groupingBy(Order::city, orderSummary()))));
System.out.println("built-in : " + Data.ORDERS.stream().mapToInt(Order::totalCents).summaryStatistics());
// a collector that earns its keep: the 2 most expensive orders, kept in a bounded heap (no full sort)
Collector<Order, PriorityQueue<Order>, List<Integer>> top2 = Collector.of(
() -> new PriorityQueue<>(Comparator.comparingInt(Order::totalCents)),
(q, o) -> { q.add(o); if (q.size() > 2) q.poll(); },
(a, b) -> { b.forEach(o -> { a.add(o); if (a.size() > 2) a.poll(); }); return a; },
q -> q.stream().sorted(Comparator.comparingInt(Order::totalCents).reversed()).map(Order::id).toList());
System.out.println("top 2 ids : " + Data.ORDERS.stream().collect(top2));
}
}Make the invisible visible: Run it.
custom : count=12 min=21900 max=89400 avg=44141.7
parallel : count=12 min=21900 max=89400 avg=44141.7
per city : {Bengaluru=count=7 min=24900 max=68700 avg=41057.1, Mysuru=count=5 min=21900 max=89400 avg=48460.0}
built-in : IntSummaryStatistics{count=12, sum=529700, min=21900, average=44141.666667, max=89400}
top 2 ids : [9, 7]What you see: The custom collector gave the same answer sequentially and in parallel: 12 orders, minimum 21,900, maximum 89,400, average 44,141.7. It also worked as the downstream of groupingBy (seven Bengaluru orders, five Mysuru). The built-in IntSummaryStatistics agrees. The top-two collector returned order ids [9, 7], the two most expensive orders, using at most two stored elements.
Why: Each thread filled its own Summary and the combiner merged them. That is why the parallel run matches the sequential one.
Hand loop
Mutable locals, no reuse.
long n = 0; int min = MAX, max = MIN;
for (Order o : orders) {
n++;
min = Math.min(min, o.totalCents());
max = Math.max(max, o.totalCents());
}Collector
Reusable and parallel-safe.
Summary s = orders.stream()
.collect(orderSummary());
var byCity = orders.stream().collect(
groupingBy(Order::city, orderSummary()));The shift: The summarising logic is written once, named, and usable at the end of any pipeline or inside any grouping.
Land it A custom collector is worth it when no built-in gives my result or I need a bounded structure like a top-N heap, and I write supplier, accumulator, combiner and finisher with one container per thread.
- "What do the Characteristics mean?"
-
They are hints that let the library optimise.
IDENTITY_FINISHsays the container is the final result, so the finisher is skipped.CONCURRENTsays the accumulator is safe to call from several threads on one shared container, so the library may use a single container for all threads.UNORDEREDsays the result does not depend on encounter order, which allows faster parallel execution.If you do not say
CONCURRENT, the library gives each thread its own container and merges at the end. That is the safe default, and the one the demo uses.Use
CONCURRENTonly with a container that is itself thread-safe (such as aConcurrentHashMap) and an accumulator that does an atomic update. Getting it wrong gives wrong results in parallel only, which tests rarely catch.Start with no characteristics except
IDENTITY_FINISHwhere it applies. Add others only when a measurement says you need them. - "How do I know my combiner is correct?"
-
A combiner must merge two partial results so that the final answer equals the sequential answer, whichever way the elements were split. For the summary: add counts and sums, take the smaller minimum, the larger maximum. For a top-two heap: add all of one heap into the other and trim to two.
Test it with a parallel stream on a large input and compare with the sequential result, many times. The demo does this once. A better test splits the input into random chunks, collects each, merges them in random order and checks the answer.
Common combiner bugs: forgetting to merge one field, merging in a way that depends on order (a non-associative merge), and returning a new object while also changing an old one.
Even if you never run parallel, write the combiner properly. The library may call it, and someone will add
parallel()one day. - "Why not just use a loop with an accumulator object?"
-
For a one-off, a loop is fine and often simpler. The collector pays off in three cases. When you need the same summary in several places: one named
orderSummary()beats five copies of a loop. When you want it as a downstream collector insidegroupingBy: a loop cannot do that, you would write nested loops with a map. And when you want to run it in parallel without writing any thread code.It is also testable on its own: feed it a stream of three orders and check the summary.
The cost is the boilerplate of four functions. The demo's collector is twenty lines, so it is not worth it for something used once.
My threshold: a custom collector when it will be used in three or more places, or when it must be a downstream collector.
- "When is IntSummaryStatistics enough, and when is it not?"
-
IntSummaryStatistics(and itsLongandDoubleversions) gives count, sum, min, average and max for one number per element, in one pass, and it is parallel-safe. For "statistics of order totals" that is exactly what you need, viamapToInt(Order::totalCents).summaryStatistics()orCollectors.summarizingInt(Order::totalCents).It is not enough when you want a statistic that depends on several fields at once (revenue per delivered minute), a median or percentiles (which need all values or an approximate sketch), a distinct count, or a combination of different statistics with different filters.
For a median, collect to a sorted list and pick the middle, or use a library with streaming quantiles. A one-pass exact median is not possible without storing values.
So: use the built-in summary for plain min, max, sum, count and average, and write a collector for anything it cannot express.
Q54. "Gatherers (24): windowFixed, windowSliding, fold, scan and mapConcurrent."
Reveal answer
Strong answer A gatherer is an intermediate stream operation you can write yourself (question 18). The JDK ships five ready-made ones in java.util.stream.Gatherers, all final in Java 24. You attach them with stream.gather(...).
windowFixed(n)cuts the stream into consecutive lists ofnelements. The last list may be shorter. Use for batches: send 100 rows per bulk insert.windowSliding(n)produces overlapping windows that move one element at a time: [1,2,3], [2,3,4], [3,4,5]. Use for moving averages and "compare with the previous" logic.scan(initial, function)emits the running result after each element, like a running total. The output has as many elements as the input.fold(initial, function)reduces everything to one value, but as a stage: it emits a single element at the end, and the stream continues. It is areducethat you can put in the middle of a pipeline.mapConcurrent(max, function)maps with up tomaxcalls running at once on virtual threads, keeping the output in input order. Use for many slow calls: ask a service for 10 riders at a time.
The first four are sequential, order-dependent stages. The last one is for waiting, not computing, and it stops on the first failure by cancelling the in-flight calls.
Before Java 24 these needed loops, a library (Guava's Lists.partition), or an executor with a list of futures. They were preview in 22 and 23, so --release 23 rejects them.
A caution: they are final, but the Gatherer interface for writing your own is advanced. Most developers will use the five built-ins and rarely write one.
Picture it Delivered QuickBite order totals run through each of the five, with the six-call mapConcurrent timed.
The setup: Q54_Gatherers.java takes the eight delivered order totals. It applies windowFixed(3), windowSliding(3) (and averages each window), scan (running revenue) and fold (one total). Then it runs six fake service calls of 200 ms with mapConcurrent(3, ...), recording the peak number in flight and whether each call ran on a virtual thread.
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.*;
public class Q54_Gatherers {
public static void main(String[] args) {
// delivered orders, in id order
List<Integer> totals = Data.ORDERS.stream().filter(o -> o.status().equals("DELIVERED")).map(Order::totalCents).toList();
System.out.println("totals : " + totals);
System.out.println("windowFixed(3) : " + totals.stream().gather(Gatherers.windowFixed(3)).toList());
System.out.println("windowSliding(3): " + totals.stream().gather(Gatherers.windowSliding(3)).limit(3).toList() + " ...");
System.out.println(" 3-order average: " + totals.stream().gather(Gatherers.windowSliding(3))
.map(w -> w.stream().mapToInt(Integer::intValue).average().orElse(0)).map(d -> Math.round(d)).toList());
System.out.println("scan (running) : " + totals.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
System.out.println("fold : " + totals.stream().gather(Gatherers.fold(() -> 0, Integer::sum)).findFirst().get());
// mapConcurrent: like map, but up to N calls in flight; output order is kept
var inFlight = new AtomicInteger(); var peak = new AtomicInteger();
long t0 = System.nanoTime();
List<String> out = Stream.of("menu", "price", "eta", "stock", "promo", "rider").gather(Gatherers.mapConcurrent(3, s -> {
peak.accumulateAndGet(inFlight.incrementAndGet(), Math::max);
try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); }
inFlight.decrementAndGet();
return s.toUpperCase() + "@" + Thread.currentThread().isVirtual();
})).toList();
System.out.println("mapConcurrent(3): " + out);
System.out.println(" peak in flight " + peak + ", " + (System.nanoTime() - t0) / 1_000_000 + " ms for 6 x 200 ms calls");
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}Make the invisible visible: Run it.
totals : [54700, 29700, 46900, 27400, 24900, 27600, 89400, 23800]
windowFixed(3) : [[54700, 29700, 46900], [27400, 24900, 27600], [89400, 23800]]
windowSliding(3): [[54700, 29700, 46900], [29700, 46900, 27400], [46900, 27400, 24900]] ...
3-order average: [43767, 34667, 33067, 26633, 47300, 46933]
scan (running) : [54700, 84400, 131300, 158700, 183600, 211200, 300600, 324400]
fold : 324400
mapConcurrent(3): [MENU@true, PRICE@true, ETA@true, STOCK@true, PROMO@true, RIDER@true]
peak in flight 3, 416 ms for 6 x 200 ms calls
// measured on the course machine (12 cores); your numbers will differWhat you see: Fixed windows gave three lists of 3, 3 and 2 totals. Sliding windows overlapped by two elements, and their three-order averages ran 43,767, 34,667 and on. scan produced the running revenue ending at 324,400, which fold gave as a single value. mapConcurrent(3) never had more than 3 calls in flight, every call ran on a virtual thread (@true), the output kept the input order, and six 200 ms calls took 416 ms: two rounds of three.
Why: A window or a running total needs to remember earlier elements, which a plain map cannot. A gatherer keeps that state for you.
Before 24
Running total with a loop.
List<Integer> run = new ArrayList<>();
int sum = 0;
for (int t : totals) {
sum += t;
run.add(sum);
}Gatherers.scan
A pipeline stage.
List<Integer> run = totals.stream()
.gather(Gatherers.scan(() -> 0,
Integer::sum))
.toList();The shift: The state (the running sum) lives in the gatherer, so the pipeline stays one expression.
Land it windowFixed batches, windowSliding overlaps, scan keeps a running result, fold collapses to one value and mapConcurrent runs bounded concurrent calls, all as pipeline stages.
- "When would I use windowFixed in a real service?"
-
Batching. Inserting 10,000 rows one by one is slow, and 10,000 rows in one statement may be too large. This sends 500 at a time:
batching with a gathererruns offlinerows.stream() .gather(Gatherers.windowFixed(500)) .forEach(batch -> repo.saveAll(batch))It is also useful for paging through an API that accepts a list of ids, and for chunking messages before sending them to Kafka.
Each window is a separate list, not a view of the source, so keeping one is safe. Treat it as read-only anyway.
A caution: if the stream comes from a database cursor, the whole pipeline is still lazy, so only one window is in memory at a time, which makes it memory-friendly for big exports.
Before Java 24, the common answer was Guava's
Lists.partitionfor lists, or a counter in a loop for streams. - "What is the difference between scan and fold?"
-
scanemits an element for every input: the running result after each one. For inputs 1, 2, 3 with addition it emits 1, 3, 6.foldemits one element at the very end: 6. Both take an initial value supplier and a combining function.Use
scanwhen you want the history, such as a running balance after each transaction or cumulative revenue per day. Usefoldwhen you want the single final value but inside the pipeline, so that more stages can follow. Outside a pipeline,reducedoes the second job.Both are inherently sequential, because each result depends on the one before. They will not speed up in a parallel stream.
The
scanin the demo's output ends with 324,400, which is exactly whatfold(andreduce) produce, a good sanity check for any running-total code. - "How does mapConcurrent handle failure and ordering?"
-
Ordering: the results come out in the same order as the inputs, even though the calls finish in any order. The gatherer holds finished results until earlier ones are ready.
Failure: the first exception thrown by any call cancels the calls still running (they are interrupted) and no new calls start, and the exception comes out of the stream's terminal operation. You do not get partial results. It behaves like structured concurrency for one pipeline stage.
Concurrency is bounded by the
maxargument, which is the number in flight, not the number of threads, since the tasks run on virtual threads. That makes it a clean way to respect a rate limit:mapConcurrent(5, this::callPartner)never has more than five calls at once.It is for blocking calls. For CPU-heavy functions use a parallel stream or a fixed pool instead, since virtual threads give no extra CPU.
- "Are gatherers lazy and short-circuiting like other stages?"
-
Yes. A gatherer is a stage like any other. It processes elements as they arrive, and a downstream operation such as
limitorfindFirstcan end the stream early.windowFixedfollowed byfindFirstreads only the first window's worth of elements.A gatherer can also decide to stop on its own. Its integrator returns
falseto say "no more input", which is how you write something like "take elements until the running total passes 1000".Some gatherers must hold elements back: a window waits to be full, and a
mapConcurrentholds results until earlier ones finish. At the end of the input, a finisher emits what is left, such as the shorter last window.So the rules from the earlier questions apply: nothing runs without a terminal operation, and the pipeline does as little work as the end demands.
These six questions are about the one-word change from stream() to parallelStream(): how the work is split, which threads run it, when it gets faster and when it silently gets wrong or slow.
Q55. "How does a parallel stream split the work, and which thread pool runs it?"
Reveal answer
Strong answer A parallel stream uses fork and join: split the data into pieces, process the pieces on several threads, and combine the results. Three parts are involved.
The splitter. The source provides a Spliterator, a splittable iterator. Its trySplit() hands back roughly the first half of the remaining elements and keeps the rest. The framework splits again and again until the pieces are small enough, which gives a tree of tasks. An ArrayList or an array splits perfectly into halves. A LinkedList or Stream.iterate splits badly, because it cannot jump to the middle.
The pool. Tasks run on the common fork-join pool, ForkJoinPool.commonPool(), one pool shared by the whole JVM (every parallel stream, and some CompletableFuture work too). Its default parallelism is the number of cores minus one, so on the course machine's 12 cores it is 11 threads. The thread that called the terminal operation also takes part in the work, so 12 threads work in all.
The combiner. Each piece produces a partial result. Partial results are combined in encounter order for ordered operations, up the tree, until one result remains.
Consequences: the pool is shared, so one badly behaved parallel stream (one that blocks, for instance) slows every other parallel stream in the application (question 57). And the speed-up depends on the source's ability to split, the cost per element and the combiner's cost.
You can use a private pool by submitting the stream's terminal operation as a task to your own ForkJoinPool. It works in practice and is not officially guaranteed, so treat it as a workaround.
Picture it A 16-element list split into leaves by hand, the pool size on this machine, and a count of which threads handled one million elements.
The setup: Q55_Split.java prints the cores and the common pool's parallelism. It splits a 16-element list with trySplit() down to pieces of two and prints the tree. Then it runs a parallel IntStream of one million elements, counting work per thread name.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class Q55_Split {
static void split(Spliterator<Integer> s, String indent, int minSize) {
long size = s.estimateSize();
Spliterator<Integer> left = size > minSize ? s.trySplit() : null; // trySplit hands back the FIRST half
if (left == null) { System.out.println(indent + "leaf of " + size); return; }
System.out.println(indent + "split " + size + " -> " + left.estimateSize() + " + " + s.estimateSize());
split(left, indent + " ", minSize); split(s, indent + " ", minSize);
}
public static void main(String[] args) {
System.out.println("cores = " + Runtime.getRuntime().availableProcessors()
+ ", common pool parallelism = " + ForkJoinPool.commonPool().getParallelism());
List<Integer> list = IntStream.range(0, 16).boxed().toList();
split(list.spliterator(), "", 2);
Map<String, Integer> who = new ConcurrentSkipListMap<>();
IntStream.range(0, 1_000_000).parallel().forEach(i -> who.merge(Thread.currentThread().getName(), 1, Integer::sum));
System.out.println("threads that did work: " + who.size());
who.forEach((k, v) -> System.out.println(" " + k + " -> " + v));
List<Integer> out = list.parallelStream().map(i -> i * 10).toList(); // combined in ENCOUNTER order
System.out.println(out);
System.out.println("main thread helps too: " + who.containsKey("main"));
}
}Make the invisible visible: Run it.
cores = 12, common pool parallelism = 11
split 16 -> 8 + 8
split 8 -> 4 + 4
split 4 -> 2 + 2
leaf of 2
leaf of 2
split 4 -> 2 + 2
leaf of 2
leaf of 2
split 8 -> 4 + 4
split 4 -> 2 + 2
leaf of 2
leaf of 2
split 4 -> 2 + 2
leaf of 2
leaf of 2
threads that did work: 12
ForkJoinPool.commonPool-worker-1 -> 250000
ForkJoinPool.commonPool-worker-10 -> 93750
ForkJoinPool.commonPool-worker-11 -> 109375
ForkJoinPool.commonPool-worker-2 -> 78125
ForkJoinPool.commonPool-worker-3 -> 46875
ForkJoinPool.commonPool-worker-4 -> 62500
ForkJoinPool.commonPool-worker-5 -> 31250
ForkJoinPool.commonPool-worker-6 -> 62500
ForkJoinPool.commonPool-worker-7 -> 46875
ForkJoinPool.commonPool-worker-8 -> 62500
ForkJoinPool.commonPool-worker-9 -> 46875
main -> 109375
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
main thread helps too: trueWhat you see: The machine has 12 cores and the common pool has parallelism 11. The sixteen elements split into halves again and again, down to eight leaves of two. The one million elements were handled by twelve threads: eleven commonPool-worker threads and the main thread, with uneven shares (the first worker did 250,000 and another 31,250). The parallel map and toList() still returned the numbers in source order.
Why: The tree shape (16 to 8 to 4 to 2) is how the work is divided. Uneven shares are normal, because the pool steals work from busy threads.
Sequential
One thread walks the list.
// thread: main
// [0 1 2 3 4 5 6 7 8 9 ...]
// main does all elements, one at a timeParallel
Halves handed to workers.
// [0..7] -> worker-1 [8..15] -> worker-2
// each half splits again, as needed
// partial results combined in orderThe shift: The data is cut into pieces like a tree, and the pool's threads take pieces until none are left.
Land it A parallel stream splits its Spliterator into halves, runs the pieces on the shared common fork-join pool of cores minus one threads plus the caller, and combines partial results in order.
- "How do I change the size of the common pool?"
-
With a system property when the JVM starts:
-Djava.util.concurrent.ForkJoinPool.common.parallelism=4. It sets the number of common-pool threads (not counting the caller) for the whole JVM. It must be set before the pool is first used, so it cannot be changed later from code reliably.Lower it when a service shares the machine with other work and you want parallel streams to take at most a few cores. Raise it rarely, because CPU-bound work gains nothing from more threads than cores.
In containers, the JVM sees the container's CPU limit, not the host's cores, so an app limited to 2 CPUs gets a pool of one thread, which makes parallel streams nearly useless. Check
availableProcessors()in the container.The better answer for blocking work is a different tool (virtual threads, question 57), not a bigger common pool.
- "What is a Spliterator and which sources split well?"
-
A
Spliteratortraverses elements like an iterator, but it can also split off part of its remaining data into another Spliterator, and it knows its size and characteristics (ordered, sized, distinct, sorted, immutable). The stream framework uses these to decide how to cut the work.Sources that split well: arrays,
ArrayList,IntStream.range,HashSetandTreeSet(reasonably) andConcurrentHashMap. Sources that split poorly:LinkedList(must walk to the middle),Stream.iterateandStream.generate(each element depends on the previous or is produced one at a time),BufferedReader.lines()and anything reading I/O.Question 58 measured the
LinkedListagainst theArrayList.If your source splits poorly and the work is heavy, copy the data into an
ArrayListfirst, then go parallel. The copy is cheap compared with the heavy work. - "Does the thread that called the stream take part?"
-
Yes. The calling thread joins in: it runs one of the pieces itself rather than waiting idle. That is why the demo's work counts include
main, and why the number of threads doing work (12) is the pool's 11 plus one.It matters in two ways. If the caller is a request thread in a web server, it is busy with the stream during the call, which is expected. And if the calling thread is itself a common-pool thread (a parallel stream started from inside another parallel stream), the framework can run both on the same pool, with some risk of the pool running out of threads when tasks block.
Do not start a blocking operation from inside a parallel stream task. It occupies a precious common-pool thread, and with no spare thread for the nested work the pool can stall.
When you need a stream that does not use the common pool at all, run the pipeline in your own
ForkJoinPool, or do not go parallel. - "How are the partial results combined, and does the order survive?"
-
For operations that have an encounter order, such as
toList(),collect(toList()),mapthentoList()andfindFirst, the framework combines pieces left to right. The demo'stoList()printed[0, 10, 20, ...]in source order from a parallel stream. That order is guaranteed for ordered sources.The combination happens up the task tree: each internal node merges its two children's results. For collectors, that is where your combiner function runs (question 53). For
sum, the partial sums are added.What is not ordered is the processing: lambdas run in any order and at the same time on different elements, which is why side effects must be avoided.
If order does not matter, calling
unordered()can let some operations (distinct,limit,findAny) run faster in parallel.
Q56 · Scenario. "A parallelStream sum gives a different answer on every run. Why?"
Reveal answer
Strong answer Almost always the cause is a shared variable updated from several threads: forEach(i -> total += i). The += is three steps (read, add, write back), and two threads can read the same old value, so one of the two additions is lost. How many are lost depends on timing, so every run is different. It is the same lost-update race as count++ from two threads.
Two other causes are less common but real. A non-associative operation in reduce: subtraction, division or "average of two". A parallel stream groups the elements in a different way from the sequential one, and for these operations the grouping changes the answer. Floating point: adding doubles is not exactly associative, so a different grouping gives a result that differs in the last digits. (DoubleStream.sum() reduces this with compensated summation, so it is often stable, but a hand-written reduce(0.0, Double::sum) can differ.)
Fix: remove the shared variable and let the stream compute: sum(), reduce(0, Integer::sum) with an associative operation, summingLong or collect. If you must count from inside a lambda, use LongAdder or AtomicLong. For money, use integer paise as in this chapter, so no floating point is involved.
Diagnostic habit: run the pipeline several times and compare. A race gives a different wrong number each time, a non-associative reduce gives the same wrong number every time (the split is deterministic), and a floating-point grouping gives tiny differences.
Picture it The shared-variable race five times, the correct sum, a subtraction reduce, and floating-point grouping.
The setup: Q56_WrongSum.java sums 1 to 1,000,000 into a shared long from a parallel forEach five times (expected 500,000,500,000). It then uses sum(), runs a subtraction reduce sequentially and in parallel, and compares a boxed reduce(Double::sum) with DoubleStream.sum() on two million doubles.
import java.util.*;
import java.util.stream.*;
public class Q56_WrongSum {
static long shared = 0; // BUG 1: a shared variable
public static void main(String[] args) {
System.out.println("expected sum of 1..1,000,000 = " + 1_000_000L * 1_000_001L / 2);
for (int run = 1; run <= 5; run++) {
shared = 0;
LongStream.rangeClosed(1, 1_000_000).parallel().forEach(i -> shared += i);
System.out.println("run " + run + ": shared += i -> " + shared);
}
System.out.println("fixed: sum() -> " + LongStream.rangeClosed(1, 1_000_000).parallel().sum());
// BUG 2: a reduce operation that is not associative: (a - b) - c != a - (b - c)
for (int run = 1; run <= 3; run++)
System.out.println("reduce(0, a - b) parallel run " + run + " -> "
+ IntStream.rangeClosed(1, 100).boxed().parallel().reduce(0, (a, b) -> a - b)
+ " (sequential gives " + IntStream.rangeClosed(1, 100).boxed().reduce(0, (a, b) -> a - b) + ")");
// SURPRISE 3: double addition is not associative, so grouping changes the last digits
Random rnd = new Random(42);
double[] xs = rnd.doubles(2_000_000).map(d -> d * 1000).toArray();
List<Double> boxed = Arrays.stream(xs).boxed().toList();
System.out.println("reduce(Double::sum) sequential: " + boxed.stream().reduce(0.0, Double::sum));
System.out.println("reduce(Double::sum) parallel : " + boxed.parallelStream().reduce(0.0, Double::sum));
System.out.println("DoubleStream.sum() sequential: " + Arrays.stream(xs).sum() + " (compensated summation)");
System.out.println("DoubleStream.sum() parallel : " + Arrays.stream(xs).parallel().sum());
System.out.println("long sum is exact in any order: " + Arrays.stream(xs).mapToLong(d -> (long) d).parallel().sum()
+ " = " + Arrays.stream(xs).mapToLong(d -> (long) d).sum());
}
}Make the invisible visible: Run it.
expected sum of 1..1,000,000 = 500000500000
run 1: shared += i -> 252277726154
run 2: shared += i -> 272354703167
run 3: shared += i -> 166895156328
run 4: shared += i -> 150031546899
run 5: shared += i -> 176413562566
fixed: sum() -> 500000500000
reduce(0, a - b) parallel run 1 -> 0 (sequential gives -5050)
reduce(0, a - b) parallel run 2 -> 0 (sequential gives -5050)
reduce(0, a - b) parallel run 3 -> 0 (sequential gives -5050)
reduce(Double::sum) sequential: 1.0002280085544958E9
reduce(Double::sum) parallel : 1.000228008554497E9
DoubleStream.sum() sequential: 1.0002280085544968E9 (compensated summation)
DoubleStream.sum() parallel : 1.0002280085544968E9
long sum is exact in any order: 999228163 = 999228163What you see: The five racy runs gave 286,612,217,632, 175,436,312,560, 118,792,859,432, 225,111,390,673 and 181,048,250,057: all different, and all far below the true 500,000,500,000. sum() gave exactly that value. The subtraction reduce gave 0 in parallel and -5050 sequentially, the same each time, which is wrong in a different way. The boxed double reduce differed between sequential and parallel in the last digits (...958E9 against ...97E9), while DoubleStream.sum() gave the same value both ways.
Why: Lost updates make the first kind unpredictable. A deterministic split makes the second kind repeatable but still wrong.
Shared variable
Threads overwrite each other.
long[] total = {0};
LongStream.rangeClosed(1, 1_000_000)
.parallel()
.forEach(i -> total[0] += i); // raceStream result
Each thread has its own sum.
long total = LongStream
.rangeClosed(1, 1_000_000)
.parallel()
.sum(); // 500000500000The shift: The library gives every thread a private partial sum and adds them at the end.
Land it A wrong parallel sum means a shared variable is racing, or the operation is not associative; I let the stream do the summing and use an atomic only when I must count from inside a lambda.
- "Why does the subtraction reduce give 0 in parallel, always the same value?"
-
Subtraction is not associative:
(a - b) - cis nota - (b - c). The sequential stream computes((0 - 1) - 2) - 3 ...and gets -5050. A parallel stream splits the range into parts, reduces each part starting from the identity 0, then combines partial results with the same function, so signs and groupings change.The answer is repeatable because the split of an
IntStream.rangeis deterministic. The same tree of pieces is formed each time. So you get one wrong answer, always. That is why a unit test with a fixed input can pass in sequential mode and a code review can miss it.The lesson is the reduce contract: the function must be associative, and the identity must be neutral.
Integer::sumandMath::maxqualify. Subtraction does not.If you need "first minus all the others", compute it explicitly:
first - rest.sum(). - "How can floating-point addition differ between runs?"
-
Doubles have limited precision, so
(a + b) + cmay differ froma + (b + c)in the last bits. A parallel sum groups the numbers differently from a sequential one, so the totals can differ in the last digits, as the boxedreduce(Double::sum)shows:1.0002280085544958E9sequentially,1.000228008554497E9in parallel.The split is deterministic here, so the parallel result repeated across my runs. With a different number of cores or a different pool size the split could change, and with it the last digits. Code that compares such totals for equality can then fail on another machine.
DoubleStream.sum()andaverage()use compensated (Kahan) summation, so they track the error and are more stable. That is why they gave the same answer both ways.The cleanest fix for money is integers (paise), so addition is exact. For measurements, compare with a tolerance.
- "What is the right way to count from inside a parallel lambda?"
-
Use
LongAdderorAtomicLong.AtomicLong.incrementAndGet()is a safe read-modify-write using a hardware compare-and-set.LongAdderis faster under heavy contention because it spreads the updates over several cells and adds them up when you read.That is for side counts such as progress or metrics. If the count is the result, let the stream produce it:
count(),summingLong,counting().A plain
volatile longdoes not help:volatilemakes the read and write visible, but+=is still three steps, so updates are still lost.The chapter's section on atomics measures the cost of these under contention. For a counter updated a million times, a
LongAdderbeats a lock by a wide margin. - "How do I test for this kind of bug?"
-
Run the code many times with a large input, since small inputs rarely expose a race. The demo used a million elements and lost most of the sum in each of five runs. Run a parallel version and a sequential version and assert equal results. If they differ, there is a shared state or a non-associative operation.
Make the machine busy while you test: run the test with different pool sizes (
-Djava.util.concurrent.ForkJoinPool.common.parallelism=1and=16) so that the split changes. A bug that appears only with one setting is still a bug.Static analysis helps: tools flag a lambda that modifies a captured variable or collection in a stream. Add them to the build.
And keep a rule: parallel streams get a test that runs them several times and compares with the sequential answer.
Q57 · Scenario. "A parallelStream that calls a REST API made the endpoint slower and froze other endpoints. Why?"
Reveal answer
Strong answer Two problems stack up. First, a parallel stream runs on the common fork-join pool, which has only cores minus one threads (11 here). It was built for CPU work, where one thread per core keeps every core busy.
A REST call is blocking: the thread sits idle for 200 ms waiting for the network. With 12 workers and 48 calls, the work is done 12 at a time, so 48 calls of 200 ms take four rounds, about 800 ms, not 200 ms. The pool's size, chosen for computing, caps the throughput of waiting.
Second, the pool is shared by the whole JVM. While those threads wait on the network, every other parallel stream in the application, and anything else using the common pool (including some CompletableFuture async stages), has nobody to run on. In the demo, a harmless 1,000-element stream took 1,119 ms while another stream hogged the pool, and 102 ms on a quiet machine. That is how one slow endpoint "freezes" unrelated ones.
Fix: do not use parallel streams for blocking work. Choose a tool made for waiting: an ExecutorService with virtual threads (Executors.newVirtualThreadPerTaskExecutor()), or Gatherers.mapConcurrent(n, ...) inside a stream, or CompletableFuture with your own executor. A semaphore or the mapConcurrent bound limits the load on the downstream service.
Also add a timeout to every remote call. A call without one can block a pool thread for ever.
Picture it 48 fake calls of 200 ms on the common pool and on virtual threads, then the damage to an innocent parallel stream.
The setup: Q57_BlockingParallel.java simulates a REST call with Thread.sleep(200). It runs 48 calls in a parallelStream and with a virtual-thread executor. Then a "hog" thread starts a parallel stream of 48 sleeps of 500 ms, and an innocent parallel stream of 1,000 tasks of 1 ms runs at the same time and again on a quiet machine.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class Q57_BlockingParallel {
static void rest(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
public static void main(String[] args) throws Exception {
System.out.println("common pool parallelism = " + ForkJoinPool.commonPool().getParallelism());
List<Integer> ids = IntStream.rangeClosed(1, 48).boxed().toList();
long t0 = System.nanoTime();
ids.parallelStream().forEach(id -> rest(200)); // 48 "REST calls" of 200 ms each
System.out.println("48 blocking calls, parallelStream : " + ms(t0) + " ms (48 x 200 / 12 workers = 800)");
t0 = System.nanoTime();
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
ids.forEach(id -> exec.submit(() -> rest(200)));
}
System.out.println("48 blocking calls, virtual threads : " + ms(t0) + " ms");
// the damage to somebody else: a second, unrelated parallel stream must share the same 11 workers
Thread hog = new Thread(() -> IntStream.range(0, 48).parallel().forEach(i -> rest(500)), "hog");
hog.start();
Thread.sleep(100);
t0 = System.nanoTime();
long n = IntStream.range(0, 1000).parallel().mapToObj(i -> { rest(1); return i; }).toList().size(); // 1000 x 1 ms of "work"
System.out.println("innocent stream while the hog runs : " + ms(t0) + " ms for 1000 x 1 ms");
hog.join();
t0 = System.nanoTime();
IntStream.range(0, 1000).parallel().mapToObj(i -> { rest(1); return i; }).toList().size();
System.out.println("same innocent stream on a quiet machine : " + ms(t0) + " ms");
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}Make the invisible visible: Run it.
common pool parallelism = 11
48 blocking calls, parallelStream : 803 ms (48 x 200 / 12 workers = 800)
48 blocking calls, virtual threads : 221 ms
innocent stream while the hog runs : 1119 ms for 1000 x 1 ms
same innocent stream on a quiet machine : 102 ms
// measured on the course machine (12 cores); your numbers will differWhat you see: The common pool has 11 workers. 48 blocking calls took 803 ms on it (48 times 200 ms divided by 12 threads is 800) and 221 ms on virtual threads. The innocent stream took 1,119 ms while the hog held the pool, against 102 ms alone, eleven times slower for no fault of its own.
Why: Virtual threads are cheap enough to give each waiting call its own thread. The common pool has a handful of threads and shares them with everyone.
Parallel stream
12 threads for 48 waits.
ids.parallelStream()
.forEach(id -> callPartner(id));
// 48 x 200 ms / 12 threads = 800 ms
// other parallel streams starveVirtual threads
One thread per call.
try (var ex = Executors
.newVirtualThreadPerTaskExecutor()) {
ids.forEach(id ->
ex.submit(() -> callPartner(id)));
} // about 200 msThe shift: Blocking work needs a thread per wait, and virtual threads make that cheap and keep the shared pool free.
Land it The common pool is sized for CPU work and shared by the whole JVM, so blocking calls in a parallel stream throttle themselves and starve other streams; I use virtual threads or mapConcurrent for I/O.
- "Can I just make the common pool bigger?"
-
You can (
-Djava.util.concurrent.ForkJoinPool.common.parallelism=100), and it hides the symptom, but it is the wrong lever. The pool is shared by everything, so you now have 100 platform threads, each with a 1 MB stack, serving all parallel streams. CPU-bound work gains nothing from them, while the memory cost and the context switching are real. And it is a global setting that other code in the process was not written for.It also does not remove the risk of starvation. It moves the limit. With enough concurrent blocking calls you hit the larger limit and see the same freeze.
A dedicated executor per kind of work isolates the problem: the partner calls cannot take threads from the report generator. That is the principle of bulkheads: separate pools so one failure cannot sink the rest.
Virtual threads give you the isolation cheaply, since each task has its own thread and the limit is the semaphore you choose.
- "How do I limit the load on the REST service I am calling?"
-
Two limits matter: how many calls you make at once, and how many per second. For concurrency, use a
Semaphore(acquire before the call, release infinally) orGatherers.mapConcurrent(10, ...), which keeps at most 10 calls in flight. Do not rely on pool size as a limit, because with virtual threads the pool is not the limit any more.For rate (calls per second), use a rate limiter library (Resilience4j's
RateLimiteror Guava'sRateLimiter), or a scheduled executor that releases permits.And add a timeout and a retry with back-off on each call, so a slow partner does not hold your threads, and a failing one is not hit harder.
A good default: concurrency limit of ten, timeout of two seconds and at most two retries, adjusted from the partner's documented limits.
- "Is a parallel stream ever right for I/O?"
-
Rarely. It can be acceptable for a one-off script that reads many local files on a machine where nothing else matters, since disk reads do release the CPU. But the framework does not know the work is blocking, cannot add threads when workers wait, and sizes everything for CPU.
The common pool does have a mechanism for blocking (
ForkJoinPool.managedBlock), andCompletableFutureuses it in a few places, but ordinary I/O in a stream lambda does not.For anything in a server, use an executor designed for waiting. Compare the options: parallel stream (CPU work), fixed thread pool (limited blocking, sized by a formula),
CompletableFuturewith an executor (composition) and virtual threads (simple blocking code at scale). Question 100 gives the full decision table.The one-line rule: parallel streams are for computing, not for waiting.
- "How do I see that the common pool is the bottleneck?"
-
Take a thread dump (
jcmd PID Thread.print). If the threads namedForkJoinPool.commonPool-worker-Nare all inTIMED_WAITINGor in a socket read, the pool is saturated with blocking calls.Check
ForkJoinPool.commonPool().getActiveThreadCount(),getQueuedSubmissionCount()andgetQueuedTaskCount()in a debug endpoint or Flight Recorder. A growing queue with all threads active means more work than workers.Look at latency: if unrelated endpoints that use parallel streams or async stages become slow together, the shared pool is the likely cause.
Once you know, the fix is to take the blocking work off the common pool, not to tune the pool.
Q58. "When does a parallel stream actually help? Give measurable criteria."
Reveal answer
Strong answer A parallel stream helps only when five conditions hold together. Think of them as a checklist you must be able to tick with measurements, not feelings.
- Enough work: the total work is large. A common rule of thumb is that N (elements) times Q (cost per element) should be above roughly 10,000 microseconds. A million cheap additions can be too little. A thousand heavy computations can be enough.
- CPU-bound work: the lambda computes and does not wait. Blocking (I/O, locks, sleeps) wastes the few pool threads (question 57).
- A source that splits well: arrays,
ArrayList,IntStream.range. NotLinkedList,iterateor readers. - Independent elements and cheap merging: no shared state, no order-dependent stages (
limit,findFirst,forEachOrdered) and a combiner that is cheap compared with the work. - Free cores: the machine has spare cores right now. On a busy server where requests already use all cores, a parallel stream adds overhead and no speed.
And always measure the actual workload, sequential against parallel, with realistic data, a warmed-up JVM and several runs (JMH for serious work). The demo's four experiments show each outcome.
When the data lives in a database or is huge, even a well-tuned parallel stream is not the first tool: push the work to the database, or split across processes.
Picture it Four experiments: heavy work on a big range, a tiny list, many trivial additions, and a LinkedList against an ArrayList.
The setup: Q58_WhenHelps.java first warms up the JIT. It counts primes up to 3,000,000 sequentially and in parallel, sums a 100-element list 2,000 times each way, adds 5,000,000 numbers, and sums 2,000,000 boxed integers from an ArrayList and a LinkedList, best of five.
import java.util.*;
import java.util.stream.*;
public class Q58_WhenHelps {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; (long) d * d <= n; d++) if (n % d == 0) return false;
return true;
}
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
static void warm() { for (int i = 0; i < 3; i++) { IntStream.range(0, 200_000).filter(Q58_WhenHelps::isPrime).count(); IntStream.range(0, 200_000).parallel().filter(Q58_WhenHelps::isPrime).count(); } }
public static void main(String[] args) {
warm();
long t0 = System.nanoTime(); long a = IntStream.rangeClosed(1, 3_000_000).filter(Q58_WhenHelps::isPrime).count();
long seq = ms(t0);
t0 = System.nanoTime(); long b = IntStream.rangeClosed(1, 3_000_000).parallel().filter(Q58_WhenHelps::isPrime).count();
long par = ms(t0);
System.out.printf("1) CPU-heavy, big N (primes up to 3,000,000): sequential %d ms, parallel %d ms, speed-up %.1fx, same=%b%n", seq, par, seq / (double) par, a == b);
List<Integer> tiny = IntStream.range(0, 100).boxed().toList();
t0 = System.nanoTime(); for (int i = 0; i < 2000; i++) tiny.stream().mapToInt(x -> x * 2).sum(); long s2 = ms(t0);
t0 = System.nanoTime(); for (int i = 0; i < 2000; i++) tiny.parallelStream().mapToInt(x -> x * 2).sum(); long p2 = ms(t0);
System.out.printf("2) tiny list (100 cheap elements) x 2000 runs : sequential %d ms, parallel %d ms%n", s2, p2);
int[] arr = new Random(42).ints(5_000_000, 0, 1000).toArray();
t0 = System.nanoTime(); long x = Arrays.stream(arr).asLongStream().sum(); long s3 = ms(t0);
t0 = System.nanoTime(); long y = Arrays.stream(arr).parallel().asLongStream().sum(); long p3 = ms(t0);
System.out.printf("3) big N but trivial work (5,000,000 additions): sequential %d ms, parallel %d ms%n", s3, p3);
List<Integer> array = IntStream.range(0, 2_000_000).boxed().collect(Collectors.toCollection(ArrayList::new));
List<Integer> linked = new LinkedList<>(array);
long s4 = timeIt(array, false), p4 = timeIt(array, true), s5 = timeIt(linked, false), p5 = timeIt(linked, true);
System.out.printf("4) summing 2,000,000 boxed ints: ArrayList seq %d / par %d ms, LinkedList seq %d / par %d ms%n", s4, p4, s5, p5);
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
static long timeIt(List<Integer> l, boolean par) {
long best = Long.MAX_VALUE;
for (int r = 0; r < 5; r++) { long t0 = System.nanoTime(); long s = (par ? l.parallelStream() : l.stream()).mapToLong(Integer::longValue).sum(); best = Math.min(best, ms(t0)); }
return best;
}
}Make the invisible visible: Run it with a 1 GB heap.
1) CPU-heavy, big N (primes up to 3,000,000): sequential 1591 ms, parallel 286 ms, speed-up 5.6x, same=true
2) tiny list (100 cheap elements) x 2000 runs : sequential 6 ms, parallel 80 ms
3) big N but trivial work (5,000,000 additions): sequential 12 ms, parallel 23 ms
4) summing 2,000,000 boxed ints: ArrayList seq 4 / par 3 ms, LinkedList seq 6 / par 15 ms
// measured on the course machine (12 cores); your numbers will differWhat you see: (1) CPU-heavy: 1,591 ms sequential against 286 ms parallel, a 5.6 times speed-up with the same answer. (2) Tiny list: 6 ms sequential against 80 ms parallel, parallel more than ten times slower. (3) Five million trivial additions: 12 ms against 23 ms, parallel slower. (4) The LinkedList in parallel (15 ms) was slower than sequential (6 ms), while the ArrayList was slightly faster in parallel (3 against 4 ms).
Why: Splitting, scheduling and merging cost time. Only when each element takes long enough, and the source splits cleanly, does the saving beat the cost.
Parallel hurts
Cheap work, small data.
// 100 elements, x * 2
list.parallelStream()
.mapToInt(x -> x * 2).sum();
// 80 ms vs 6 ms sequentialParallel helps
Heavy work, big range.
// 3,000,000 primality tests
IntStream.rangeClosed(1, 3_000_000)
.parallel().filter(Q::isPrime).count();
// 286 ms vs 1,591 ms sequentialThe shift: The same switch is a loss on the left and a gain on the right: the cost per element decides.
Land it A parallel stream helps with a lot of CPU-bound work per element, a source that splits well, independent elements and free cores, and I confirm it with a sequential-against-parallel measurement.
- "What is the N times Q rule of thumb?"
-
It comes from Doug Lea's guidance for the fork-join framework: parallelism pays off when N (number of elements) times Q (cost per element, in time) is large enough, roughly more than ten thousand microseconds (10 ms) of total work. Below that, the overhead of splitting, queueing and merging dominates.
It explains the demo. One hundred elements of a microsecond each is 100 microseconds, far below the threshold, so the parallel version lost badly. Three million primality tests are many seconds of work, far above it, so the parallel version won by 5.6 times.
Q can be small if N is huge (millions of cheap operations), but the memory-bound operations then compete for bandwidth and the gain is limited, as the third experiment shows.
It is a rule of thumb for deciding what to measure first, not a replacement for measuring.
- "Why was the speed-up 5.6 times and not 12 times?"
-
Several reasons. Not all of the 12 threads were free: other jobs were running on the course machine at the time, so do not trust the exact figure. Splitting and merging cost something. The work per element varies (larger numbers take longer to test for primality), so some pieces finish earlier and the pool must steal work to rebalance. And the machine's 12 "cores" may include hyper-threads, which share execution units.
A speed-up of 60 to 80 per cent of the core count is typical for well-suited, CPU-bound work on a quiet machine. Beyond that, memory bandwidth and the sequential parts of the program limit it (Amdahl's law).
If you see less than two times on eight or more cores for supposedly heavy work, suspect something: shared state, boxing, a poorly splitting source, or a busy machine.
Measure on hardware similar to production. A laptop's result does not transfer to a container with two CPUs.
- "Why is the LinkedList result worse in parallel?"
-
To split a
LinkedListinto halves, the spliterator has to walk through the nodes to find the middle, and its splits are uneven (it takes batches from the front). There is no random access, so the work of splitting is itself sequential, and the pieces are small and cache-unfriendly. AnArrayListsplits in constant time by index arithmetic.In the demo, the
LinkedListparallel sum (15 ms) was slower than sequential (6 ms), while theArrayListwas not worse. Differences between sequentialArrayListandLinkedList(4 against 6 ms) show the cache effect even without parallelism.If you must run a heavy computation on a
LinkedList, copy it to anArrayListfirst. Likewise forStream.iterate, where each element depends on the one before and splitting cannot be clean.The general lesson: the data structure decides whether parallelism is even possible.
- "How do I measure properly?"
-
The simplest honest method is to warm up the JVM (run the code a few times first so the JIT compiler has optimised it), then time several runs and take the best or the median, as the demo does. A single cold run measures class loading and interpretation, not your pipeline.
For serious decisions use JMH, the OpenJDK micro-benchmark harness. It handles warm-up, forks a fresh JVM for each trial, prevents the compiler from removing code whose result is unused, and reports error bars.
Measure on production-like data and hardware, with the load you expect: a parallel stream that wins alone on an idle machine may lose when twenty requests run it at once and compete for the same cores.
And measure both time and the effect on other work, as in question 57. A parallel stream that is 30 per cent faster and makes every other endpoint slower is not an improvement.
Q59. "findFirst versus findAny, and forEach versus forEachOrdered, in parallel."
Reveal answer
Strong answer In a parallel stream, order is something you pay for. Each pair of operations differs in whether it respects the stream's encounter order (the order of the source, such as list order).
findFirst returns the first element in encounter order. In parallel, a worker that finds a match in a later piece must wait to learn whether an earlier piece has one. findAny returns whichever match is found first by any worker. It may differ from run to run, and it is faster in parallel. If you only need "some match", findAny or anyMatch says so.
forEach in parallel runs the action on each element as soon as a worker reaches it, in any order, from several threads at once. forEachOrdered runs the action in encounter order, one element at a time in sequence, even though the work before it can still be parallel. Workers that are ahead have to wait for their turn.
The cost of order shows in a measurement: an action that takes 50 ms for 24 elements took 102 ms with forEach and 1,210 ms with forEachOrdered in the demo. The action itself is the slow part, and ordering made it sequential.
Other order-sensitive operations: limit, skip, takeWhile and distinct on ordered streams. Calling unordered() on the stream tells the library that order does not matter, which can make them faster.
Collecting to a list with toList() keeps source order without forEachOrdered, because the combine step runs in order. So collect, and then loop, instead of ordering a side effect.
Picture it findAny against findFirst five times, forEach against forEachOrdered output, and the time cost of ordering.
The setup: Q59_Ordering.java runs findAny and findFirst for multiples of 7 on the numbers 1 to 1000 five times. It appends the numbers 1 to 12 with forEach and forEachOrdered on a parallel stream, then times 24 sleeps of 50 ms in each.
import java.util.*;
import java.util.stream.*;
public class Q59_Ordering {
public static void main(String[] args) {
List<Integer> nums = IntStream.rangeClosed(1, 1000).boxed().toList();
for (int run = 1; run <= 5; run++) {
Integer any = nums.parallelStream().filter(n -> n % 7 == 0).findAny().get();
Integer first = nums.parallelStream().filter(n -> n % 7 == 0).findFirst().get();
System.out.println("run " + run + ": findAny -> " + any + " findFirst -> " + first);
}
System.out.println();
List<Integer> small = IntStream.rangeClosed(1, 12).boxed().toList();
StringBuffer a = new StringBuffer(), b = new StringBuffer();
small.parallelStream().forEach(n -> a.append(n + " "));
small.parallelStream().forEachOrdered(n -> b.append(n + " "));
System.out.println("forEach : " + a);
System.out.println("forEachOrdered : " + b);
System.out.println("collect/toList keeps order without forEachOrdered: " + small.parallelStream().map(n -> n * n).toList());
// the price of order: forEachOrdered makes workers wait for their turn
long t0 = System.nanoTime();
IntStream.range(0, 24).parallel().forEach(i -> { try { Thread.sleep(50); } catch (InterruptedException e) {} });
long t1 = System.nanoTime();
IntStream.range(0, 24).parallel().forEachOrdered(i -> { try { Thread.sleep(50); } catch (InterruptedException e) {} });
long t2 = System.nanoTime();
System.out.println("24 x 50 ms in the terminal action: forEach " + (t1 - t0) / 1_000_000 + " ms, forEachOrdered " + (t2 - t1) / 1_000_000 + " ms");
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}Make the invisible visible: Run it.
run 1: findAny -> 658 findFirst -> 7
run 2: findAny -> 658 findFirst -> 7
run 3: findAny -> 658 findFirst -> 7
run 4: findAny -> 161 findFirst -> 7
run 5: findAny -> 658 findFirst -> 7
forEach : 2 8 11 9 4 3 10 12 7 1 5 6
forEachOrdered : 1 2 3 4 5 6 7 8 9 10 11 12
collect/toList keeps order without forEachOrdered: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]
24 x 50 ms in the terminal action: forEach 102 ms, forEachOrdered 1210 ms
// measured on the course machine (12 cores); your numbers will differWhat you see: findFirst returned 7 every time. findAny returned 658 every time on this machine, which is allowed but not guaranteed: the contract says any match, and a different core count or load may give a different one. forEach gave the order 2 8 11 9 4 3 10 12 7 1 5 6, forEachOrdered gave 1 to 12, and toList() kept source order by itself. Sleeping 24 times for 50 ms took 102 ms with forEach and 1,210 ms with forEachOrdered.
Why: forEachOrdered lets only one element's action run at a time, in order. The expensive part you put inside it is therefore no longer parallel.
forEach
Fast, any order.
// action runs on many threads
nums.parallelStream()
.forEach(n -> out.append(n));
// 2 8 11 9 4 3 10 12 7 1 5 6forEachOrdered
Source order, slower.
nums.parallelStream()
.forEachOrdered(n -> out.append(n));
// 1 2 3 4 5 6 7 8 9 10 11 12
// actions run one at a timeThe shift: Ordering the side effect serialises it, so keep the heavy work before it and only the ordered write inside it.
Land it findAny and forEach ignore encounter order and are fast in parallel, while findFirst and forEachOrdered respect it at a cost, and toList keeps order without the penalty.
- "When is findAny safe to use?"
-
When any match will do and the stream has no meaningful order for you: "is there some delivered order", "find any available rider", "pick any server that is up". In those cases,
findAnyoranyMatchexpresses the intent and lets the parallel stream finish as soon as any worker finds one.Do not use it when the choice must be repeatable: "the cheapest order", "the oldest", "the first in the file". For those, sort or use
min,maxorfindFirst.On a sequential ordered stream,
findAnyin practice returns the first element, which can make tests pass and production (parallel) misbehave. That is another reason to write the right one.The contract is explicit:
findAnymay return any element and may return a different one on different runs. Treat any single answer as a coincidence. - "What does unordered() do?"
-
unordered()is a hint that the stream's encounter order does not matter to you. It does not shuffle anything. It permits the library to use faster algorithms for operations that normally preserve order:distinctcan use a concurrent set instead of tracking first occurrences,limitcan take any n elements rather than the first n, andfindFirstwould behave likefindAnyin effect.Use it when order really is irrelevant: counting distinct values, taking "some 100 samples", collecting to a set. Do not use it before
toList()if the list order should follow the source.On a sequential stream, it changes nothing observable.
It is a promise you make to the library. If you break it (you do care about order), you get a different result and no error.
- "How do I print results from a parallel stream in order?"
-
Best: do not print from the stream. Collect first (
toList(),collect(joining(...))), which is ordered, and print the result from the calling thread afterwards. The heavy per-element work stays parallel, and the output is in order with no waiting.If you must act per element in order, use
forEachOrdered, but keep the expensive work in earlier stages (map) so that only the cheap final action is serialised. In the demo, the sleep was inside the ordered action, which is the worst case.For logging, a unique id per element in the message and a sort afterwards is often enough.
If output order is needed and the work is cheap, just use a sequential stream or a loop.
- "Why is limit slow on an ordered parallel stream?"
-
To return the first n elements, the library must know which elements are the first n in encounter order, so workers cannot just take any elements they like. Pieces to the right have to wait or have their results discarded if the left pieces already supply enough. That is extra coordination, and wasted work.
With
unordered(),limit(n)may return any n elements and can stop as soon as n are found by any worker. A quick test over a range of fifty million numbers showed no visible difference between the two, because a range splits cheaply and an orderedlimitstill stops early there, so the effect appears mainly for sources where preserving order is costly.The rule is the same: if order matters, pay for it knowingly. If it does not, say so with
unordered().Always check with a measurement on your own data, as the benefit is not uniform.
Q60 · Design. "Design a report over 50 million order rows: sequential stream, parallel stream, or something else?"
Reveal answer
Strong answer I would first ask where the rows live and what the report needs, because the best answer is often "none of the above". Then I would work down a ladder, stopping at the first rung that meets the deadline.
- Let the database do it. If the rows are in a database, a
GROUP BYquery with the right index (or a summary table, or a materialised view) returns a few hundred rows, and the 50 million never leave the server. This is the fastest and cheapest answer, and chapter E8 covers it. - Stream with constant memory. If you must process the rows in Java, read them as a cursor or a file stream and fold each into a small accumulator (a
long[]per restaurant). One pass, almost no memory, no parallelism needed. - Use primitives, not objects. If the data must be in memory, keep columns as
int[]andlong[]. In the demo, 5,000,000 rows as objects used about 187 MB, so 50 million is about 1.9 GB of heap before any work starts, and the garbage collector will feel it. Arrays of primitives are roughly ten times smaller. - Then parallelism. If one pass is still too slow, split by range (by day or partition) and aggregate each part in parallel into private accumulators, then merge. A parallel stream over primitive ranges does exactly this.
- Scale out. If it no longer fits one machine, use a batch engine or a columnar store (Spark, ClickHouse, Parquet with DuckDB), or pre-aggregate as the data arrives (Kafka, chapter E17).
The demo measures rungs 3 and 4 at one tenth of the size. Plain objects with a sequential stream took 66 to 118 ms, the same objects with a parallel stream 86 to 144 ms (slower), a primitive loop 5 to 18 ms, and a parallel collect into per-thread primitive arrays 3 ms after warm-up. The lesson is that the data layout mattered more than the parallelism.
What I would not do: parallelStream() on a list of 50 million objects loaded into the heap, which risks an out-of-memory error and is not faster.
The decision also depends on the freshness needed: a nightly report can use batch, a live dashboard needs pre-aggregation.
Picture it The same grouping of revenue by restaurant on five million synthetic rows, four ways.
The setup: Q60_BigReport.java builds five million rows with new Random(42), as two primitive arrays and as a list of two-int records, reports the heap used, and runs three rounds of four versions: sequential object stream with groupingBy, parallel with groupingByConcurrent, a plain loop over the arrays and a parallel IntStream.collect with a private long[] per thread. It runs with -Xmx1g.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Q60_BigReport {
record Row(int restaurant, int cents) {} // two ints: the part of an order the report needs
static final int N = 5_000_000, RESTAURANTS = 50;
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
public static void main(String[] args) {
Random rnd = new Random(42);
int[] restaurant = new int[N], cents = new int[N];
for (int i = 0; i < N; i++) { restaurant[i] = rnd.nextInt(RESTAURANTS); cents[i] = 9900 + rnd.nextInt(40000); }
List<Row> rows = IntStream.range(0, N).mapToObj(i -> new Row(restaurant[i], cents[i])).toList();
Runtime rt = Runtime.getRuntime(); System.gc();
System.out.println("5,000,000 rows as objects + arrays use about " + (rt.totalMemory() - rt.freeMemory()) / 1_000_000 + " MB of heap");
for (int round = 1; round <= 3; round++) {
long t0 = System.nanoTime();
Map<Integer, Long> a = rows.stream().collect(groupingBy(Row::restaurant, summingLong(Row::cents)));
long tA = ms(t0); t0 = System.nanoTime();
Map<Integer, Long> b = rows.parallelStream().collect(groupingByConcurrent(Row::restaurant, summingLong(Row::cents)));
long tB = ms(t0); t0 = System.nanoTime();
long[] c = new long[RESTAURANTS];
for (int i = 0; i < N; i++) c[restaurant[i]] += cents[i];
long tC = ms(t0); t0 = System.nanoTime();
long[] d = IntStream.range(0, N).parallel().collect(() -> new long[RESTAURANTS],
(acc, i) -> acc[restaurant[i]] += cents[i],
(x, y) -> { for (int k = 0; k < RESTAURANTS; k++) x[k] += y[k]; });
long tD = ms(t0);
boolean same = a.get(7) == c[7] && b.get(7) == c[7] && d[7] == c[7];
System.out.printf("round %d: objects seq %3d ms | objects parallel %3d ms | primitive loop %3d ms | primitive parallel collect %3d ms | same=%b%n",
round, tA, tB, tC, tD, same);
}
System.out.println("// measured on the course machine (12 cores); your numbers will differ");
}
}Make the invisible visible: Run it.
5,000,000 rows as objects + arrays use about 187 MB of heap
round 1: objects seq 118 ms | objects parallel 144 ms | primitive loop 11 ms | primitive parallel collect 39 ms | same=true
round 2: objects seq 66 ms | objects parallel 86 ms | primitive loop 18 ms | primitive parallel collect 3 ms | same=true
round 3: objects seq 84 ms | objects parallel 93 ms | primitive loop 5 ms | primitive parallel collect 3 ms | same=true
// measured on the course machine (12 cores); your numbers will differWhat you see: The objects and arrays used 187 MB. After the first (cold) round, the sequential object stream took 66 to 84 ms and the parallel one 86 to 93 ms, so the parallel version was slower. The primitive loop took 5 to 18 ms. The parallel primitive collect took 3 ms in rounds two and three. All four agreed on the answer (the check compares restaurant 7).
Why: Objects force the CPU to chase pointers and the merge of maps costs more than the sum it saves. Primitive arrays let each thread run through its own range with no objects and a tiny merge.
Objects in memory
Heavy and not faster in parallel.
List<Row> rows = loadAll(); // 50M objects
rows.parallelStream().collect(
groupingByConcurrent(Row::restaurant,
summingLong(Row::cents)));Push down or primitives
Light, and fast.
// in the database:
// SELECT restaurant, SUM(cents)
// FROM orders GROUP BY restaurant;
long[] sums = new long[50]; // in Java
cursor.forEach(r -> sums[r.rest()] += r.cents());The shift: The fastest rows are the ones you never move, and the next fastest are the ones you never wrap in objects.
Land it For 50 million rows I would aggregate in the database first, otherwise stream once into primitive accumulators, and only then split the range across threads after measuring.
- "Why was the parallel object stream not faster here?"
-
Because the work per element is tiny (one addition into a map), and the cost of building and merging maps across threads is of the same size. The parallel version creates a partial
HashMapfor each piece and merges them, and the concurrent version has all threads update one sharedConcurrentHashMap, where updates to the same key (only 50 keys) contend.With 50 keys and five million rows, many threads hit the same few entries, so they wait for each other. The sequential version has no coordination at all.
Memory also matters: 5 million records are pointers scattered over the heap, so threads spend most of their time waiting for memory, not computing. More threads share the same memory bandwidth.
That is the typical result for aggregation of cheap values: parallelism gives little, and a better data layout gives a lot. Heavy per-row computation (parsing, scoring) is where parallel streams pay off.
- "How would you read 50 million rows without holding them all?"
-
Stream them. In JDBC, set a fetch size and iterate the
ResultSet(or use Spring'sJdbcTemplate.queryForStreamor a repository method that returns aStream), and update the accumulator for each row. In a file,Files.lines(path)reads lazily, one line at a time. Both keep memory flat.Close the resource (try-with-resources), keep the transaction open while you read, and consume inside it. For databases that load the whole result by default (PostgreSQL does unless a fetch size and a transaction are set), set the fetch size explicitly or the driver will pull everything into memory first.
Then keep only what you need from each row: two ints, not the whole row object. The rest is garbage right away.
If the source is sorted by the grouping key (by restaurant, say), you can even finish each group and release it, keeping only one open at a time.
- "When would a parallel stream be right for this report?"
-
When each row needs real computation, such as parsing a JSON blob, scoring a model or computing a distance, and the rows are already in an array or
ArrayList. Then the per-element cost is high, the source splits well, and the work is independent: the five conditions from question 58.It can also be right for the final step of splitting the data by day or partition, with each part aggregated independently into its own accumulator, then merged. That uses all cores with little contention.
Check that the machine really has spare cores. A parallel stream inside a web request on a busy server competes with other requests. For a nightly batch job, which owns the machine, it is a good fit.
And measure on the real data size. Results on 5 million rows do not predict 50 million exactly, especially for memory pressure and garbage collection.
- "How do I make the report fast on repeat runs?"
-
Do not recompute. Pre-aggregate: a summary table updated incrementally (a row per restaurant and day, updated as orders arrive or by a nightly job), or a materialised view that the database refreshes. Reading 150 summary rows is instant, whatever the number of orders.
For streaming data, aggregate in the stream: Kafka Streams or a consumer that keeps running totals per key and writes them out (chapter E17).
A cache of the finished report with a short time-to-live suits a dashboard that many people open. Cache the result, not the 50 million rows.
The cheapest rows to aggregate are the ones that were aggregated once, by something that already had to touch each of them.
15 · DrillConcurrency from Zero — Q61–Q100
The last forty questions follow the chapter's own order: threads and races, executors and futures, locks and concurrent collections, CompletableFuture, and finally virtual threads and structured concurrency. Each answer builds from the single idea underneath, then adds the mechanism, the number and the judgement a senior round listens for.
Every demo was run on the course machine (12 cores, JDK 25, with JDK 21 for the pinning comparison). Races and hangs are non-deterministic, so the answers report what happened in the runs I made, and your numbers will differ. Programs and their output live in code/e21-modern-java/F/.
These answers teach the idea once and then point to the deeper question. Where E3 (the Java interview drill) has a question on the same topic, the Strong answer ends with its number: E3 Q141–Q180 cover threads and synchronization, and E3 Q181–Q220 cover pools, futures, locks, collections and virtual threads. Say yours first, then reveal.
These questions start from one thread and one counter, and build up to the bugs every concurrent program meets: lost updates, invisible writes and deadlock. Each answer is something you can show with a few lines and a stopwatch.
Q61. "Runnable versus Callable — what can a Callable do that a Runnable cannot?"
Reveal answer
The real test Whether you say the two real differences (a return value and a checked exception) and then name the thing that makes them usable: an executor that hands back a Future.
Strong answer A Runnable is a task with one method, void run(). It returns nothing and cannot throw a checked exception. A Callable<V> is a task with V call() throws Exception. It returns a value of type V and may throw anything.
Those two differences matter because a thread has no natural place to put a result. Thread.start() returns void, and an exception thrown inside run() dies with that thread. A Runnable therefore has to write its answer into shared state (a field, an array, a queue) and the caller has to know when it is safe to read.
A Callable fixes both. You give it to ExecutorService.submit(...). The executor runs it on a pool thread and gives you a Future, a receipt for the result that is not ready yet. future.get() waits for the answer, or throws ExecutionException wrapping whatever the task threw.
You cannot give a Callable to new Thread(...), because Thread only accepts a Runnable. That is the practical reason Callable and executors travel together.
Both are functional interfaces (one abstract method), so a lambda works for either. The compiler picks by shape: a lambda that produces a value becomes a Callable, a lambda with a statement body and no value becomes a Runnable. submit(() -> 42) and submit(() -> System.out.println(1)) both compile.
The primer builds this up in Threads from zero and Executors. For interviews, E3 Q189 lists what plain Future cannot do, which is the next step after Callable.
Picture it A QuickBite rider-ETA lookup that sometimes fails. The same work is written as a Callable and as a Runnable.
The setup: fetchEta(orderId) sleeps 200 ms, returns minutes, and throws a checked Exception for order 13. Two pool threads run the Callables. A separate plain thread runs the Runnable version, which has to smuggle the answer out through an array.
import java.util.concurrent.*;
public class Q61Callable {
static int fetchEta(int orderId) throws Exception {
Thread.sleep(200);
if (orderId == 13) throw new Exception("rider service down");
return 25 + orderId;
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
Callable<Integer> ok = () -> fetchEta(7);
Callable<Integer> bad = () -> fetchEta(13);
Future<Integer> f1 = pool.submit(ok);
Future<Integer> f2 = pool.submit(bad);
System.out.println("eta for order 7 = " + f1.get() + " min");
try {
f2.get();
} catch (ExecutionException e) {
System.out.println("order 13 failed: " + e.getCause());
}
// A Runnable cannot return a value: the result must go through shared state.
int[] box = new int[1];
Runnable r = () -> { try { box[0] = fetchEta(7); } catch (Exception e) { /* nowhere to throw */ } };
Thread t = new Thread(r); t.start(); t.join();
System.out.println("runnable via shared box = " + box[0]);
pool.shutdown();
}
}Make the invisible visible: Run it and watch where the value and the exception come out.
eta for order 7 = 32 min
order 13 failed: java.lang.Exception: rider service down
runnable via shared box = 32What you see: f1.get() returned 32. The failing task did not crash anything. Its exception came out of f2.get() wrapped in an ExecutionException, with the original exception as the cause.
Why: The Runnable version needed a one-element array to carry the result, and it had to swallow the checked exception, since run() cannot declare one. The Callable version carried both through the Future.
Runnable
No result, no checked exception. The answer goes through shared state.
int[] box = new int[1];
Runnable r = () -> {
try { box[0] = fetchEta(7); }
catch (Exception e) { /* lost */ }
};
Thread t = new Thread(r);
t.start(); t.join();
int eta = box[0];Callable
Returns the value. A checked exception is carried to the caller.
Callable<Integer> c = () -> fetchEta(7);
Future<Integer> f = pool.submit(c);
int eta = f.get(); // waits, or throws
// ExecutionException wraps any failureThe shift: A Callable turns "run this and hope" into "run this and give me a receipt that holds the answer or the failure".
Land it I reach for Callable whenever a task produces an answer or can fail, because the Future carries both back instead of leaving me to invent shared state.
- "Can I run a Callable without an executor?"
-
Yes, but there is no automatic way to get its result out. A
Callableis just an object with acall()method, so you can call it directly on the current thread:c.call(). That is a normal method call and does no concurrency at all.To run it on another thread without an executor, wrap it in a
FutureTask.FutureTaskimplements bothRunnableandFuture, so you can hand it tonew Thread(task).start()and later calltask.get().FutureTaskWay.javaruns offlineFutureTask<Integer> task = new FutureTask<>(c); new Thread(task).start(); int eta = task.get();That is exactly what an executor does inside:
submit(callable)wraps your task in aFutureTaskand runs it on a worker. I use the direct form only in tests. In real code the executor also owns the thread lifecycle, which is the part that goes wrong by hand. - "What happens to an exception thrown inside a Runnable on a plain Thread?"
-
The thread dies and the JVM prints the stack trace to standard error through the thread's uncaught exception handler. The code that started the thread is never told. In the Q62 style of bug, the caller carries on as if all was well.
You can install a handler per thread with
t.setUncaughtExceptionHandler(...), or one for all threads withThread.setDefaultUncaughtExceptionHandler(...). It gets the thread and the exception, which is enough to log or alert.But a handler is a last resort, not a result channel. It cannot return a fallback value to whoever needed the answer. With a
Callablethe failure is part of the result:get()throws, the caller decides.My rule for production: log through a handler as a safety net, and use
FutureorCompletableFuturefor anything whose failure the caller must react to. Q72 shows the same difference betweenexecuteandsubmit. - "Why does Callable use Exception and not RuntimeException?"
-
Because
call()is declaredthrows Exception, so the task body may call methods that throw checked exceptions, such asIOExceptionorInterruptedException, without catching them inside a lambda.That matters for the most common thing tasks do: block.
Thread.sleep,queue.take()and network calls all declare checked exceptions. In aRunnableyou must wrap every one in try/catch, and the usual result is an empty catch block that hides the failure.The price is on the caller side.
future.get()throwsExecutionException, and you unwrap it withgetCause(). You also handleInterruptedException, becauseget()itself waits.That unwrap step is the clumsy part, and one reason
CompletableFutureexists (Q87). For plain pools I accept the wrapper, since one wrapper type is simpler than many different checked types leaking out. - "Is Callable ever better than a Runnable plus a CompletableFuture?"
-
Often they combine.
CompletableFuture.supplyAsync(Supplier)takes aSupplier, not aCallable, and aSuppliercannot throw checked exceptions. So a lambda that callsThread.sleepneeds a try/catch there, whilepool.submit(callable)does not.My choice depends on what I do with the result. If I only need the value at one point (a batch of independent jobs and then
invokeAll),Callablewith plainFutureis the least machinery. If I want to chain steps, combine results, or add timeouts and fallbacks, I useCompletableFuture(primer: CompletableFuture).A small bridge covers the gap: wrap the checked call in a helper that rethrows as
CompletionExceptionorUncheckedIOException, and use it insidesupplyAsync.So neither is "better".
Callableis the simplest producer of a single result, andCompletableFutureis the better pipeline.
Q62 · Scenario. "A developer calls thread.run() instead of start(). What happens?"
Reveal answer
Strong answer Nothing concurrent happens. run() is an ordinary method, so calling it executes the body on the calling thread, one statement after another, and returns only when the body finishes. No new thread is created. start() is the method that asks the JVM to create a thread and arrange for it to call run().
The program still compiles, still works and still gives the right answer. That is why this bug survives code review. The only symptom is speed: three jobs that should overlap now take the sum of their times.
The reliable test is to print Thread.currentThread().getName() inside the task. With run() it prints main every time. With start() it prints Thread-N names, or your pool names.
The second difference is state. A thread can be started only once. A second start() throws IllegalThreadStateException, while run() can be called as often as you like because it is only a method.
The third difference is exceptions. An exception thrown inside run() called directly propagates to the caller like any method call. Inside a started thread it is not seen by the starter at all.
A good habit prevents the bug entirely: do not create Thread objects by hand, give work to an executor with submit or execute. Then there is no run() to call by mistake. The primer shows this fix as Start, not run, and E3 Q143 asks the same question as a code-review scenario.
Picture it A QuickBite job that sends three notifications of 200 ms each, written both ways.
The setup: The same work(...) method prints its thread name, sleeps 200 ms, and is run first with run() and then with start() plus join(). Total times are measured.
public class Q62RunVsStart {
static void work(String label) {
System.out.println(label + " on " + Thread.currentThread().getName());
try { Thread.sleep(200); } catch (InterruptedException e) { }
}
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
for (int i = 0; i < 3; i++) { int n = i; new Thread(() -> work("run() #" + n)).run(); }
System.out.println("run(): " + (System.nanoTime() - t0) / 1_000_000 + " ms");
t0 = System.nanoTime();
Thread[] ts = new Thread[3];
for (int i = 0; i < 3; i++) { int n = i; ts[i] = new Thread(() -> work("start() #" + n)); ts[i].start(); }
for (Thread t : ts) t.join();
System.out.println("start(): " + (System.nanoTime() - t0) / 1_000_000 + " ms");
Thread t = new Thread(() -> {});
t.start(); t.join();
try { t.start(); } catch (IllegalThreadStateException e) { System.out.println("second start(): " + e); }
}
}Make the invisible visible: The thread name and the stopwatch tell the story.
run() #0 on main
run() #1 on main
run() #2 on main
run(): 604 ms
start() #0 on Thread-3
start() #1 on Thread-4
start() #2 on Thread-5
start(): 202 ms
second start(): java.lang.IllegalThreadStateExceptionWhat you see: With run() all three notifications ran on main and took 604 ms, three times 200. With start() they ran on three new threads and took 202 ms. The last line is the one-shot rule.
Why: The thread names here are Thread-3, Thread-4 and Thread-5 because three Thread objects were already created by the first loop. Unstarted threads still consume a number from the name counter.
run() — a method call
Runs on the caller. The next line waits for it.
Thread t = new Thread(() -> send());
t.run(); // runs here, on main
// main is busy until send() returns
System.out.println(Thread.currentThread());start() — a new thread
Returns at once. The body runs on a new thread.
Thread t = new Thread(() -> send());
t.start(); // runs there, on Thread-0
// main carries on immediately
t.join(); // wait only if neededThe shift: run() keeps you on one thread, while start() asks the JVM for a second one.
Land it I tell people that run() is just a method and only start() makes a thread, and I check it by printing the thread name.
- "Why does Java even allow calling run() directly?"
-
Because
run()is a public method of theRunnableinterface, and the interface has no idea whether a thread will call it. ARunnableis only a unit of work. It can be run by a thread, by an executor, by a test, or by plain code.That is useful. Unit tests often call
task.run()directly to check the logic without any concurrency. A direct-executor pattern (an executor that runs each task on the caller) uses it deliberately, for exampleRunnable::runas anExecutorin tests of async code.The cost is that nothing warns you when you meant to start a thread. Static analysis tools do: IntelliJ and SpotBugs flag a direct
Thread.run()call.So the language gives one method with two valid uses, and the habit of using executors removes the ambiguity from production code.
- "How can I prove from a log line that a task ran on its own thread?"
-
Print the thread name, or better, put it in your log format. Every mainstream logging setup can print the thread name with each line (
%tin Log4j patterns,%threadin Logback).Then read the names. If every line of a "parallel" job says
mainor the same request-handler name, the work is serial. If you seepool-2-thread-1up topool-2-thread-8, eight workers ran.Timestamps help just as much. Compute the total: the sum of task times means serial, the longest single task means parallel. In the run above, 604 ms against 202 ms made the answer obvious without reading code.
In production I also check with a thread dump (Q70): a parallel job shows several runnable worker threads, a serial one shows one.
- "Does start() run the body immediately?"
-
No.
start()returns quickly and the new thread begins running at some point after that. When exactly depends on the operating-system scheduler. It is usually within microseconds, but nothing guarantees it.That means you cannot assume ordering between the code after
start()and the body. In the run above, the order of lines from the three started threads could vary from run to run.If you need the body to finish before moving on, call
join()(Q63). If you need it to have begun, use aCountDownLatchthat the body releases first.A classic bug is printing a variable right after
start()and expecting the thread's work to be visible. It may or may not be. Always add a happens-before edge:join(), a latch, a queue, or aFuture. - "Is there any case where I want the work on the caller's thread?"
-
Yes, three. First, tests. A direct executor makes asynchronous code deterministic, so a test needs no sleeps.
Second, back-pressure.
ThreadPoolExecutor.CallerRunsPolicyruns a task on the submitting thread when the pool and its queue are full. That slows the producer down on purpose, which is often better than dropping work. Q75 shows where it sits in the decision path.Third, small work. If a task takes a microsecond, a thread hand-off costs far more than the work. Many libraries run tiny callbacks inline for that reason, which is why Q89 asks which thread runs a
CompletableFuturecallback.In all three cases the decision is explicit. The bug in this question is the unplanned version of the same thing.
Q63. "What does join() do, and what does sleep() not do?"
Reveal answer
Strong answer t.join() makes the calling thread wait until thread t has finished. It is how one thread says "I need your result, or at least your completion, before I go on". join(ms) waits at most that long and then returns anyway, so you must check t.isAlive() to know which happened.
join() also gives you a memory guarantee. Everything thread t wrote before it ended is visible to the joiner after join() returns. That is one of the happens-before rules (the promise that one action's effects are seen by another). It is why reading a plain field after join() is safe.
Thread.sleep(ms) pauses the current thread for about that long. It does not release any lock the thread holds. A thread that sleeps inside synchronized keeps the monitor, and every other thread that needs it sits in state BLOCKED for the whole sleep.
It does not wait for another thread either. It is only a timer, and the wake-up time is a minimum, not an exact time. It can also be cut short: interrupt() makes sleep throw InterruptedException.
Compare with Object.wait(), which releases the monitor while waiting (E3 Q160 covers that contrast in full). The mix-up between sleep and wait is the most common error in this area.
The primer introduces both in Threads from zero, and E3 Q141 explains the thread states you see below.
Picture it Two small experiments: join with and without a timeout, and a sleeping thread that holds a lock.
The setup: A worker sleeps 600 ms. Main joins it for 200 ms, then joins without a limit. Then a holder thread sleeps 500 ms inside synchronized while a waiter thread tries to enter the same monitor, and main reads both states.
public class Q63JoinSleep {
static final Object LOCK = new Object();
public static void main(String[] args) throws Exception {
Thread worker = new Thread(() -> {
try { Thread.sleep(600); } catch (InterruptedException e) { }
}, "worker");
worker.start();
long t0 = System.nanoTime();
worker.join(200);
System.out.println("join(200) returned after " + (System.nanoTime() - t0) / 1_000_000 + " ms, alive=" + worker.isAlive());
worker.join();
System.out.println("join() returned after " + (System.nanoTime() - t0) / 1_000_000 + " ms, alive=" + worker.isAlive());
// sleep() keeps every lock it holds
Thread holder = new Thread(() -> {
synchronized (LOCK) {
try { Thread.sleep(500); } catch (InterruptedException e) { }
}
}, "holder");
Thread waiter = new Thread(() -> { synchronized (LOCK) { } }, "waiter");
holder.start(); Thread.sleep(100);
waiter.start(); Thread.sleep(100);
System.out.println("holder is " + holder.getState() + " (sleeping, lock still held)");
System.out.println("waiter is " + waiter.getState() + " (cannot enter the lock)");
holder.join(); waiter.join();
System.out.println("waiter is " + waiter.getState());
}
}Make the invisible visible: Print elapsed time and getState().
join(200) returned after 200 ms, alive=true
join() returned after 600 ms, alive=false
holder is TIMED_WAITING (sleeping, lock still held)
waiter is BLOCKED (cannot enter the lock)
waiter is TERMINATEDWhat you see: join(200) gave up after 200 ms with the worker still alive. The plain join() returned at 600 ms. The sleeping holder showed TIMED_WAITING while the waiter showed BLOCKED. After the holder woke and left, the waiter ran to TERMINATED.
Why: BLOCKED means "waiting to enter a monitor". The holder never gave the monitor up during its sleep, so the waiter had to wait out the whole 500 ms for a lock the holder was not even using.
sleep — holds the lock
The lock stays owned for the whole pause. Others are BLOCKED.
synchronized (menuLock) {
Thread.sleep(500); // lock still held
menu = load();
}
// everyone needing menuLock waits 500 mswait — gives the lock back
The monitor is released while waiting and re-taken on wake-up.
synchronized (menuLock) {
while (!loaded) menuLock.wait();
// lock was free while we waited
use(menu);
}The shift: sleep pauses the thread but keeps its locks, while wait pauses it and lets the monitor go.
Land it I use join() to wait for a thread and get its results safely, and I never sleep while holding a lock, because the sleeper keeps everyone else out.
- "What happens if the thread being joined is interrupted while it waits?"
-
The waiting thread is the one that gets interrupted, not the thread being joined.
join()throwsInterruptedExceptionin the caller and clears its interrupt flag. The joined thread keeps running.That is a useful design for cancellation. If the main thread is told to stop (say by a shutdown hook), a blocked
join()wakes at once and the main thread can clean up, instead of waiting for a long job.The rule is the same as for any blocking call (Q63 and the interrupts bridge in the primer). Either rethrow
InterruptedExceptionor callThread.currentThread().interrupt()to restore the flag. Swallowing it hides the stop request from the code above you.E3 Q178 and Q179 cover cancellation that fails because someone swallowed the exception.
- "How is join different from Future.get() or a CountDownLatch?"
-
All three make a thread wait for something else. They differ in what the waiter learns and how general they are.
Tool Waits for Gives you Thread.joinOne thread to end Completion only, no result Future.getOne task to finish The result or the exception CountDownLatch.awaitN events, from any threads Completion only, can fire many times before the end I use
joinonly when I own the thread, which is rare in modern code. A pool thread never ends, so you cannot join it. For tasks on pools I useFuture.getorinvokeAll, and for "wait for three stations" I use a latch (Q80).All of them also create a happens-before edge, so the data written before the event is visible after the wait.
- "Why is the sleep time only approximate?"
-
Because
sleep(ms)means "do not run for at least this long". After the timer expires the thread becomes runnable, and the operating-system scheduler decides when it actually gets a CPU. On an idle machine that is within about a millisecond. On a busy one it can be tens of milliseconds.The clock matters too. Some systems have a coarse timer, and very short sleeps like
sleep(1)can take more. In the run above 200 ms came back as 200 and 600 as 600, because the machine was quiet.The consequence is that sleeping is a bad way to coordinate. Code such as "sleep 100 ms and hope the other thread is done" passes on a laptop and fails on a loaded CI server.
The fix is to wait on an event:
join, a latch, a queue or a future. I keepsleepfor simulating latency in demos and for real backoff delays, where "at least this long" is exactly what I want. - "What are the thread states, and which ones did the demo show?"
-
Java has six: NEW (created, not started), RUNNABLE (running, or ready to run), BLOCKED (waiting to enter a monitor), WAITING (waiting with no time limit, for
wait,join()orpark), TIMED_WAITING (the same with a limit, likesleep(ms)orjoin(ms)), and TERMINATED.The demo showed three of them. The holder was TIMED_WAITING because of
sleep. The waiter was BLOCKED because it wanted a monitor someone else held. At the end the waiter was TERMINATED.The useful reading rule for a thread dump: many threads BLOCKED on the same lock id point to lock contention or a deadlock. Many WAITING in a pool's
take()are idle workers, which is healthy. RUNNABLE threads in native I/O look busy but are really waiting on the network.E3 Q141 goes through all six with dump examples.
Q64. "Why does count++ lose updates with two threads? Show the bytecode."
Reveal answer
Strong answer Because count++ looks like one step but is three: read the field, add one, write the field back. Two threads can both read the same old value, both add one, and both write the same new value. Two increments happened, and the counter moved by one.
The bytecode makes the three steps visible. For a static field the compiler emits getstatic (read), iconst_1 and iadd (add), and putstatic (write). Between any two of those instructions the operating system may switch to another thread.
This kind of bug is a lost update: a read-modify-write sequence that is not atomic, meaning not indivisible. The write of the first thread is overwritten by the write of the second, and its effect disappears.
The result is not wrong every time. On a fast machine with short runs the threads may never overlap, so a test passes. That is the danger: the code is wrong on every run and visibly wrong only some of the time.
The fixes all make the three steps one indivisible unit: synchronized (a lock around it), AtomicInteger.incrementAndGet() (one hardware compare-and-swap loop), or LongAdder for heavy contention. A volatile field does not fix it, because volatile makes reads and writes visible but does not join them (Q67).
The primer shows this first race in Threads from zero and the fixes in Synchronization. E3 Q167 is the same bug in a "volatile hit counter" scenario.
Picture it Two threads add 1,000,000 each to a plain static counter, five times.
The setup: One static int count, a method inc() that does count++, and two threads that call it a million times each. The expected total is 2,000,000.
public class Q64Count {
static int count = 0;
static void inc() { count++; }
public static void main(String[] args) throws Exception {
for (int run = 1; run <= 5; run++) {
count = 0;
Thread a = new Thread(() -> { for (int i = 0; i < 1_000_000; i++) inc(); });
Thread b = new Thread(() -> { for (int i = 0; i < 1_000_000; i++) inc(); });
a.start(); b.start(); a.join(); b.join();
System.out.println("run " + run + ": expected 2000000, got " + count + " (lost " + (2000000 - count) + ")");
}
}
}Make the invisible visible: Run it five times in one JVM, then disassemble inc() with javap -c -p.
run 1: expected 2000000, got 1857541 (lost 142459)
run 2: expected 2000000, got 1963141 (lost 36859)
run 3: expected 2000000, got 1000000 (lost 1000000)
run 4: expected 2000000, got 2000000 (lost 0)
run 5: expected 2000000, got 2000000 (lost 0) static void inc();
Code:
0: getstatic #7 // Field count:I
3: iconst_1
4: iadd
5: putstatic #7 // Field count:I
8: returnWhat you see: Three of the five runs lost updates (142,459 and 36,859 short, and one run lost a full 1,000,000). Two runs happened to be correct. The bytecode of inc() is the read, the add and the write, with nothing to make them one unit.
Why: The correct runs are not proof of safety. They are the JIT compiler and the scheduler lining up. The run that lost exactly 1,000,000 is a good example of the lost-update effect at scale: one thread's whole run was overwritten by the other's later writes. Your numbers will differ.
The timeline below shows one lost update step by step. Two threads read the same value 41, both write 42, and the counter shows one increment for two calls.
// illustrative
time thread A thread B count
1 getstatic -> 41 41
2 getstatic -> 41 41
3 iadd -> 42 41
4 iadd -> 42 41
5 putstatic 42 42
6 putstatic 42 42 <- two increments, one effectPlain int
Three steps, any thread may interleave between them.
static int count;
static void inc() {
count++; // read, add, write
}
// 2 x 1,000,000 -> often fewerAtomicInteger
One atomic step, built on a hardware compare-and-swap.
static AtomicInteger count =
new AtomicInteger();
static void inc() {
count.incrementAndGet();
} // 2 x 1,000,000 -> 2,000,000The shift: The same +1 becomes safe when the read, add and write are one indivisible operation.
Land it I explain count++ as read, add, write, and I show the bytecode, because two threads can both read 41 and both write 42.
- "Does making count volatile fix it?"
-
No.
volatileguarantees that a write by one thread is visible to the next read by another thread, and that reads and writes are not reordered around it. It says nothing about joining a read and a write into one step.With a
volatile int, both threads still read 41 (a fresh, correct 41), both still add one, and both still write 42. Visibility did not help, because the bug was never staleness. It was the gap between the read and the write.The demo for Q67 shows it: a volatile counter lost updates in the same way as a plain one.
Volatile is right for a flag that one thread writes and others read (Q66), or for publishing an immutable object. For a counter use an atomic or a lock. E3 Q167 is the interview version of this question.
- "Why did one run lose exactly 1,000,000 updates?"
-
This looks odd. I did not inspect the generated code, so this is the likely explanation, not a proof. In that run the JIT compiler probably had already compiled the loop in one thread, and it may keep
countin a register for the whole loop. The loop adds a million, and only at the end writes the total back.The other thread did the same. Each wrote its own total, and the last writer won: its 1,000,000 replaced the other's 1,000,000. The final value is 1,000,000 although 2,000,000 additions happened.
That is a second effect on top of the interleaving: with no synchronization the compiler is allowed to cache a plain field in a register. This is why a data race is undefined behaviour in spirit even though Java defines what values you may see.
I do not rely on guessing which of these happened. The advice is the same in both cases: do not share a plain mutable field between threads without a lock, atomic or volatile.
- "How would I find a lost update like this in a real service?"
-
You rarely find it by reading code. You find it by a number that does not add up: a counter lower than the request count, a balance off by a few rupees, an inventory that does not match.
- Reproduce under load: run the suspect method from 8 or more threads, many iterations, and compare with the expected total. A repeat of five runs, as above, is the quickest test.
- Look for shared mutable state: a static field, a singleton's field, a field in a Spring bean (beans are singletons by default), a plain
HashMaporArrayListshared across requests. - Use tools: the jcstress harness tests concurrency outcomes systematically. SpotBugs flags some unsynchronized access to fields that are elsewhere synchronized.
Then pick the smallest fix that makes the compound action atomic, and rerun the same test many times. Passing once means little, passing 1,000 times in a loop means something.
- "When is a lost update acceptable?"
-
Only when the number is a rough statistic and nobody makes a decision on exact values. A "page views" counter whose total is off by 0.1 percent may be fine. A metric that is sampled anyway may be fine.
Even then, the cost of the safe version is tiny.
LongAdderhandles heavy contention with very low overhead (Q67, and the primer's contention timings), so there is rarely a reason to accept wrong values on purpose.Where it is never acceptable: money, stock, anything that is a rule ("no more than 1 coupon use"), ids, and any value that is used to decide. A lost update there becomes a wrong action.
My own rule is simple. If I cannot explain in one sentence why the race is harmless, I treat it as a bug. E3 Q173 pushes back on the idea that stale values are always fine.
Q65. "Race condition versus data race — what is the difference?"
Reveal answer
The real test Whether you can show that the two are independent: code can have a race condition with no data race (everything atomic, logic still wrong), and a data race with no visible race condition (a stale read the program happens to tolerate).
Strong answer A data race is a low-level fact about memory. Two threads access the same variable at the same time, at least one is a write, and there is no happens-before ordering between the accesses (no lock, volatile, atomic or join that orders them). The Java Memory Model defines it exactly. A program with a data race may see stale or surprising values.
A race condition is a higher-level fact about correctness. The result depends on the timing of operations in a way that breaks what the program is supposed to do. "Check stock, then decrement" is a race condition if two buyers can both pass the check.
They are different, and neither implies the other. You can have a race condition with no data race. Use an AtomicInteger for stock: every read and write is atomic and ordered, so there is no data race, yet two threads can both read 1, both pass if (stock > 0), and sell the last unit twice.
You can also have a data race that is not a race condition by your rules. A plain long flag read without a lock may be stale, and if the program tolerates staleness there is no incorrect outcome (a rare, deliberate design, and still fragile).
Why the difference matters: fixing a data race (make the variable volatile or atomic) does not fix a race condition. The fix for a race condition is to make the whole check-then-act sequence atomic with a lock, compareAndSet, or a data structure that offers an atomic operation (Q83, Q86).
E3 Q170 and Q173 cover data races, and Q157 covers the check-then-act race condition on a thread-safe map.
Picture it One demo of each kind, side by side.
The setup: The first part keeps stock in an AtomicInteger (no data race possible) but checks and decrements in two separate steps, with a 5 ms pause to widen the gap. Two buyers compete for one unit. The second part increments a plain int from two threads, a pure data race.
import java.util.concurrent.atomic.AtomicInteger;
public class Q65RaceKinds {
// Race condition WITHOUT a data race: every access is atomic, the logic is still wrong.
static final AtomicInteger stock = new AtomicInteger(1);
static final AtomicInteger sold = new AtomicInteger();
static void buy() {
if (stock.get() > 0) { // check
try { Thread.sleep(5); } catch (InterruptedException e) { }
stock.decrementAndGet(); // act
sold.incrementAndGet();
}
}
// Data race: plain int, no ordering between threads.
static int plain = 0;
public static void main(String[] args) throws Exception {
Thread a = new Thread(Q65RaceKinds::buy), b = new Thread(Q65RaceKinds::buy);
a.start(); b.start(); a.join(); b.join();
System.out.println("1 unit in stock, sold " + sold + ", stock now " + stock + " (no data race, still a race condition)");
Thread c = new Thread(() -> { for (int i = 0; i < 100_000; i++) plain++; });
Thread d = new Thread(() -> { for (int i = 0; i < 100_000; i++) plain++; });
c.start(); d.start(); c.join(); d.join();
System.out.println("plain int after 2 x 100000: " + plain + " (data race)");
}
}Make the invisible visible: Run it and read the stock figure.
1 unit in stock, sold 2, stock now -1 (no data race, still a race condition)
plain int after 2 x 100000: 128056 (data race)What you see: One unit was sold twice and the stock went to -1, although every operation was atomic. The plain counter lost updates too, because that is a data race.
Why: Atomic types make each single operation indivisible. They do not make the pair "check, then decrement" indivisible. Two correct atomic operations in a row are not one correct operation.
The fix: Make the check and the act one step. compareAndSet does that for a single variable.
Check then act
Two atomic steps with a gap between them.
if (stock.get() > 0) {
stock.decrementAndGet();
sold.incrementAndGet();
}
// two buyers can both pass the checkAtomic decision
One compare-and-set decides who wins the last unit.
int s;
do { s = stock.get(); if (s == 0) return; }
while (!stock.compareAndSet(s, s - 1));
sold.incrementAndGet(); // winner onlyThe shift: To remove a race condition, the unit that must be atomic is the whole decision, not each variable.
Land it I keep the two terms apart: a data race is about memory ordering, a race condition is about wrong results, and atomics fix the first but not the second.
- "Can a program have a data race and still be correct?"
-
In the strict sense, yes, but it is rarely wise. The Java Memory Model says that a program free of data races behaves as if threads take turns, which is easy to reason about. A program with a data race can still produce a result you accept, but you are now reasoning about what the model allows, not what you expect.
The standard example is
String.hashCode(). It caches its hash in a plain field without a lock. Two threads may compute the hash twice, but the answer is always the same, and aStringis immutable, so the race is benign. The JDK authors wrote it that way on purpose, with care.For application code I treat any data race as a bug to remove. The cost of an atomic or volatile is small, and the cost of reasoning about stale values is large. E3 Q173 argues the same point.
- "Which tools detect each kind?"
-
Data races have tools because they are a precise property of memory accesses. ThreadSanitizer-style detectors for the JVM exist but are not common. In practice I use the jcstress harness for small hot spots and code review for the rest.
Race conditions have no general tool, because they are about intent: only you know that "stock must never go negative". The tool that finds them is a good test: many threads, many iterations, an invariant asserted at the end.
In the demo above, the invariant was one line: sold must not exceed 1. Writing the invariant down is most of the work.
For production, assertions on invariants and metrics help: an alert on "stock below zero" would have shown this bug within minutes of the first double sale.
- "Why does a lock fix the race condition but only some atomics do?"
-
A lock makes a block of code indivisible, however many variables and steps it touches. While a thread holds the lock, no other thread runs any block guarded by the same lock.
An atomic variable makes one operation on one variable indivisible.
compareAndSetgoes a step further: it says "change this only if it still has the value I looked at", so a decision based on a read can be applied safely. That fixes check-then-act for one variable, as the demo's fix showed.When the decision spans two variables ("debit A and credit B", or "check stock and write an order row"), a single atomic cannot cover it. You need a lock around both, or a transaction in the database.
So my order of choice is: one variable, use an atomic; several variables, use a lock; data in a database, use a transaction. Q67 gives the full table.
- "Is double-checked locking a data race or a race condition?"
-
Both can appear in it, which is why it is famous. The classic broken version reads a plain field outside the lock to see whether the object is already built. That read races with the write inside the lock, so it is a data race.
The effect is that another thread can see a non-null reference to an object whose fields are not yet fully set. The program then misbehaves on timing, which is the race condition part.
Making the field
volatileremoves the data race, because the write and the read are then ordered, and that fixes it. The simpler fix is to avoid the pattern: a holder class or an enum singleton gets lazy, thread-safe initialization from the class loader, with no hand-written locking.E3 Q171 walks through why the old version failed and what the memory model says.
Q66 · Scenario. "A worker loop while (!stop) never exits after another thread sets stop = true. Why?"
Reveal answer
Strong answer Because the worker never sees the new value. stop is a plain field, and the Java Memory Model does not promise that a write by one thread becomes visible to a read in another thread unless something orders them. The worker's loop reads stop, finds false, and has no reason to read it again.
The mechanism is the JIT compiler. A loop like while (!stop) { spins++; } has no synchronization inside. The compiler may legally hoist the read of stop out of the loop, which means it reads the field once, keeps the value in a register, and turns the loop into while (true). Each CPU core also has caches, and without a barrier a core may keep using its old copy.
The symptom is a worker that is RUNNABLE and burning one full core forever, while the main thread printed "stop set". It does not happen in every JVM mode. In a debugger or before the JIT warms up, the loop may exit, which makes the bug hard to reproduce.
The fix is to give the write and the read a happens-before relationship. The smallest fix is volatile boolean stop: a write to a volatile field is visible to every later read of it, and the compiler may not hoist the read.
For anything more than a flag, use interruption: worker.interrupt() with a loop that checks Thread.currentThread().isInterrupted(), which is the standard cancellation channel and also wakes blocking calls (Q63, and the interrupts bridge in the primer).
The primer calls the fix Volatile flag. E3 Q144 is the audit-flusher version of this exact bug, and E2 The Java Memory Model has the full rules.
Picture it Two programs that differ in one word: volatile.
The setup: A worker counts spins in while (!stop). After 500 ms main sets stop = true and joins. The first program uses a plain field and runs under timeout 5, because it may never finish.
public class Q66Stop {
static boolean stop = false; // plain field
public static void main(String[] args) throws Exception {
Thread worker = new Thread(() -> {
long spins = 0;
while (!stop) { spins++; }
System.out.println("worker saw stop after " + spins + " spins");
}, "worker");
worker.start();
Thread.sleep(500);
stop = true;
System.out.println("main set stop = true");
worker.join();
System.out.println("done");
}
}Make the invisible visible: Run the plain version under timeout 5 and check the exit code, then run the volatile version.
$ timeout 5 java Q66Stop.java ; echo "exit=$?"
main set stop = true
Terminated
exit=124What you see: Main printed that it set the flag, but the program never ended. timeout killed it after five seconds (exit code 124). The worker did not print its "saw stop" line.
The fix: Change one line, static volatile boolean stop = false;, and run again.
main set stop = true
worker saw stop after 1262460972 spins
doneWhy: With volatile the worker re-read the field on every pass, saw true within a moment, and exited after about 1.26 billion spins. The same JVM, the same machine, one keyword. This hang was reproduced on this machine every time I ran it; on other machines or JVM flags the plain loop may exit, and that is exactly why it is dangerous.
Plain field
The JIT may read it once and keep it in a register.
static boolean stop;
// worker
while (!stop) { work(); }
// main
stop = true; // may never be seenVolatile field
Every read goes to memory and sees the latest write.
static volatile boolean stop;
// worker
while (!stop) { work(); }
// main
stop = true; // seen on the next loopThe shift: A volatile keyword turns a one-off cached read into a read that must follow the latest write.
Land it I say the worker never re-reads a plain field, so I make the flag volatile or use interruption, and I remember the symptom is a thread burning CPU forever.
- "Why does adding a System.out.println inside the loop sometimes make the bug disappear?"
-
Because
printlnsynchronizes internally.PrintStreamtakes a lock around each write, and taking and releasing a lock is a memory barrier: it forces the thread to see other threads' earlier writes. The loop now contains a synchronization point, so the hoist is no longer allowed.This is the reason many "visibility" bugs vanish when someone adds logging to investigate. The bug is still in the program. The logging changed the timing and the compiler's options.
The same is true of
Thread.sleepin the loop body, and of any call that synchronizes. It is a trap for debugging and for tests: a test with a print statement passes, the production code without it hangs.So I never trust a concurrency fix because "it works with logging on". I fix the ordering with
volatile, a lock or an atomic, and I test without the logging. - "Is volatile enough if the worker also has to finish its current job and then exit?"
-
Yes for the flag itself, with one caution about when the worker notices.
volatileguarantees that the next read seestrue, but the worker only reads it once per loop turn. If one turn is a 30-second download, the stop request waits up to 30 seconds.For jobs that block, a flag is not enough, because a thread blocked in
socket.read()orqueue.take()never reaches the next check. Interruption solves that:interrupt()wakessleep,wait,joinandBlockingQueuecalls with anInterruptedException.The production pattern is the combination: loop on
!Thread.currentThread().isInterrupted(), catchInterruptedExceptionand exit, and keep each turn short. Usevolatileonly for simple flags such as "paused".E3 Q178 describes what interrupt does and does not do.
- "What guarantees does volatile give, in plain words?"
-
Two things. First visibility: when thread A writes a volatile variable and thread B later reads it, B sees A's value, and also everything A wrote before that volatile write. Second ordering: the compiler and CPU may not move other reads and writes across the volatile access in a way that would break the first promise.
That second part is why volatile can safely publish an object. If A fills in a config object and then sets
volatile boolean ready = true, B readsreadyand then sees a fully filled config.What volatile does not give: atomic read-modify-write (Q64, Q67) and mutual exclusion.
flag = !flagon a volatile still has a gap between its read and write.E3 Q166 states the guarantees formally, and Q170 shows the config-then-flag pattern failing without volatile.
- "How do I test for a visibility bug?"
-
It is hard, because the bug depends on the JIT and the CPU. Three methods work in practice.
- Run the loop long enough to compile: a visibility hang needs the JIT, so a test that stops after 50 ms may pass. Run the worker for at least a second, as the demo did, with
timeoutas a watchdog. - Run it many times, in a fresh JVM: flags such as
-XX:+PrintCompilationshow when the JIT compiled the method, and the result can vary between JVM versions. - Use a harness: jcstress runs tiny concurrent tests millions of times on several memory models and reports the outcomes it saw.
For application code, the strongest tool is a rule: any field read by more than one thread must be final, volatile, atomic, or only touched under a lock. Code review for that rule finds more bugs than testing does.
- Run the loop long enough to compile: a visibility hang needs the JIT, so a test that stops after 50 ms may pass. Run the worker for at least a second, as the demo did, with
Q67. "synchronized versus volatile versus AtomicInteger — when do you use each?"
Reveal answer
Strong answer Pick by what has to be protected. volatile protects visibility of one variable. AtomicInteger (and its relatives) protects one read-modify-write on one variable. synchronized protects a block of code, which can touch many variables and run many steps as one indivisible unit.
Use volatile for a flag or a reference that one thread writes and others read, with no read-then-write on it. Examples: volatile boolean stop, a volatile Config current that is replaced as a whole with an immutable object.
Use an atomic for a counter, a sequence number, a max value or a compare-and-set decision on a single variable. incrementAndGet, accumulateAndGet and compareAndSet are lock-free: they retry in a tiny loop instead of waiting.
Use synchronized (or ReentrantLock) when an invariant spans several variables or several steps: "debit this wallet and add a ledger line", "check, then insert". It also gives visibility to everything done inside the block.
The common mistake is to use volatile where an atomic is needed. A volatile int with count++ still loses updates, as the demo below shows. The second mistake is to use several atomics for one invariant, which is the race condition of Q65.
Under very heavy contention on one counter, LongAdder beats AtomicLong because it spreads the updates over several cells (the primer's Atomic counter has timings). E3 Q166 to Q168 and Q205 cover volatile and atomics in depth.
Picture it Four counters, four threads, 500,000 increments each. Which ones reach 2,000,000?
The setup: A plain int, a volatile int, an int incremented inside a synchronized method, and an AtomicInteger, all updated in the same loop by the same four threads.
import java.util.concurrent.atomic.AtomicInteger;
public class Q67ThreeTools {
static int plain; static volatile int vol; static int syn; static final AtomicInteger atom = new AtomicInteger();
static synchronized void incSyn() { syn++; }
public static void main(String[] args) throws Exception {
Thread[] ts = new Thread[4];
for (int k = 0; k < 4; k++) {
ts[k] = new Thread(() -> {
for (int i = 0; i < 500_000; i++) { plain++; vol++; incSyn(); atom.incrementAndGet(); }
});
ts[k].start();
}
for (Thread t : ts) t.join();
System.out.println("expected 2000000");
System.out.println("plain int " + plain);
System.out.println("volatile " + vol);
System.out.println("synchronized " + syn);
System.out.println("AtomicInteger " + atom.get());
}
}Make the invisible visible: Run it and compare the totals with the expected 2,000,000.
expected 2000000
plain int 1984401
volatile 1982586
synchronized 2000000
AtomicInteger 2000000What you see: The plain and the volatile counter both lost updates (about 15,600 and 17,400 short in this run). The synchronized and atomic counters were exact.
Why: Volatile made every read and write visible, but vol++ is still three steps. Only the lock and the atomic made the three steps one. The run is non-deterministic, so the volatile loss may be larger or smaller, and some runs show none.
volatile int
Visible, but ++ is still read, add, write.
volatile int hits;
void hit() {
hits++; // still 3 steps
}
// 4 threads: totals come out shortAtomicInteger
One atomic step, no lock to wait for.
AtomicInteger hits = new AtomicInteger();
void hit() {
hits.incrementAndGet();
}
// 4 threads: always exactThe shift: Volatile fixes seeing a value, and an atomic fixes changing it safely.
Land it I choose volatile to publish a value, an atomic to change one variable safely, and a lock when several variables belong to one rule.
- "Why not just use synchronized everywhere?"
-
You can, and it is correct. The cost is in two places: speed under contention, and risk. A contended lock makes threads wait (BLOCKED), and a lock also opens the door to deadlock (Q69) once code holds more than one.
For a single counter the lock is also more machinery than needed. Under heavy contention a lock is usually slower than an atomic, and
LongAdderis faster still. The Atomic counter idiom in the primer times all three on this machine.The lock has the advantage of covering several variables and any amount of code. So my rule is: atomics for one variable, locks for invariants over several, and always the simplest tool that holds the invariant.
Since Java 24 (JEP 491) virtual threads no longer pin a carrier when blocked on a
synchronizedmonitor, which removed one old reason to avoid it in new code (Q96). - "What is compare-and-swap, in plain words?"
-
Compare-and-swap (CAS) is one CPU instruction that says: "set this memory location to
new, but only if it currently holdsexpected; tell me if it worked". The check and the write happen as one indivisible step in hardware.AtomicInteger.incrementAndGet()uses it in a loop. Read the current value (say 41). Try to CAS 41 to 42. If another thread changed it to 42 in the meantime, the CAS fails, so read again (42) and try 42 to 43. The loop repeats until a CAS succeeds.No thread is ever blocked, and no thread holds a lock that could be left held by a crash. The cost is retries when many threads fight over the same variable.
- Read:
old = value. - Compute:
new = old + 1. - Try:
compareAndSet(old, new); if false, go back to step 1.
E3 Q202 explains CAS in the interview version, and Q203 shows the ABA problem.
- Read:
- "When is volatile alone the correct answer?"
-
When exactly one thread writes the variable and many read it, or when writes replace the whole value without depending on the old one. Both are cases of "publish, don't update".
- Works: a stop or pause flag; a
volatile Map<String,Price> pricesthat a refresher thread replaces with a fresh immutable map; a "ready" marker after initialization. - Fails: any counter;
x = x + 1; "set if not set yet" (two writers can both see "not set"). - Interview takeaway: "Volatile is for publishing a value, not for changing it from several threads."
The reference-swap pattern is the most useful one in services: build the new immutable object off to the side, then one volatile write makes it live. Readers never lock and never see a half-built object.
- Works: a stop or pause flag; a
- "What about AtomicReference and the other atomics?"
-
They extend the same idea to other types.
AtomicReference<T>does CAS on an object reference.AtomicBoolean,AtomicLongand the array and field-updater versions cover the rest.LongAdderandLongAccumulatorare special: built for counting under contention, with a result you read at the end.The typical use of
AtomicReferenceis a lock-free update of an immutable state: read the current object, compute a new object from it,compareAndSet(old, new), retry on failure.updateAndGet(fn)wraps that loop.Two cautions. The function you pass may run more than once, so it must be free of side effects. And a CAS compares references, not equality, which opens the ABA problem for node-based structures (E3 Q203).
I use
AtomicReferencefor small immutable state and reach for a lock when the update gets long.
Q68. "What does synchronized guarantee besides mutual exclusion?"
Reveal answer
The real test Whether you remember the second guarantee: visibility and ordering. Unlock happens-before every later lock of the same monitor, so what one thread wrote inside the block is seen by the next thread that enters it.
Strong answer Besides keeping two threads out of a block at once, synchronized guarantees visibility: everything a thread wrote before it released a monitor is visible to the next thread that acquires the same monitor. In the language of the Java Memory Model, an unlock happens-before every later lock of the same object.
That is what makes a field safe if every access is inside synchronized on the same lock, even though the field is not volatile. On entry the thread refreshes its view of memory, and on exit it publishes its writes.
It also gives ordering. The compiler and CPU may not move reads and writes of the block across its boundaries in a way another thread could notice. Inside the block they may reorder as they like, as long as the block is only seen through the lock.
The guarantee has two limits. It applies only to threads that use the same monitor. A reader that never takes the lock gets no promise, which is the common trap: the writer synchronizes, the reader does not. The second limit is that it makes the block atomic only for other code that locks the same object.
This is why the rule is "guard every access to shared mutable state with the same lock", reads included.
The primer covers it in Synchronization, and E3 Q155 and Q156 ask exactly this: the second guarantee, and whether an unlocked read of a written-under-lock field is safe.
Picture it The writer is synchronized in both cases. Only the reader differs.
The setup: A static ready flag. Two daemon readers spin until it becomes true. One reads the plain field in the loop. The other reads through a synchronized method, the same one the writer used. Main sets the flag after 300 ms and waits a second.
public class Q68SyncVisibility {
static boolean ready = false;
static synchronized void setReady() { ready = true; }
static synchronized boolean isReady() { return ready; }
public static void main(String[] args) throws Exception {
// Reader uses a plain read; writer synchronizes. The writer's lock does not help a reader that never locks.
Thread r1 = new Thread(() -> { while (!ready) { } System.out.println("plain reader: saw ready"); }, "plain-reader");
r1.setDaemon(true); r1.start();
// Reader that locks the same monitor each time.
Thread r2 = new Thread(() -> { while (!isReady()) { } System.out.println("locking reader: saw ready"); }, "locking-reader");
r2.setDaemon(true); r2.start();
Thread.sleep(300);
setReady();
Thread.sleep(1000);
System.out.println("plain reader alive: " + r1.isAlive() + ", locking reader alive: " + r2.isAlive());
}
}Make the invisible visible: Run it and ask which reader is still alive.
locking reader: saw ready
plain reader alive: true, locking reader alive: falseWhat you see: The reader that locked the monitor saw the change and finished. The plain reader never printed and was still alive after a second. The writer's lock did nothing for a reader that did not use it.
Why: The write was published at unlock, but the plain reader never performed a matching lock, so no happens-before edge connected them. This is a timing-dependent result: on another machine the plain reader might exit.
Writer locks, reader does not
No edge connects them. The reader may never see the update.
synchronized void setReady() {
ready = true;
}
void waitReady() {
while (!ready) { } // no lock
}Both sides lock the same monitor
Unlock then lock gives visibility and ordering.
synchronized void setReady() {
ready = true;
}
synchronized boolean isReady() {
return ready;
}The shift: Mutual exclusion is half of synchronized, and the other half only works for code that takes the same lock.
Land it I answer that synchronized also gives visibility and ordering, but only between threads that lock the same object, so every read needs the lock too.
- "Does the synchronized block make the variable volatile?"
-
Not in the way a keyword does, but for the code that uses the lock the effect is stronger. A volatile read or write is visible to everyone. A
synchronizedblock makes all the variables it touches visible to the next thread in the block, not only one.The effect is limited to threads that use that monitor. A thread that reads the field without the lock sees no promise. A
volatilefield gives its promise to every reader, with no lock to remember.So the two are different tools. Volatile is cheap and covers one variable and any reader. Synchronized covers many variables and many steps but only for participants that lock.
E3 Q156 is the direct interview version: a field written only in a synchronized block, read without the lock.
- "What does happens-before mean in plain words?"
-
It is a promise about order of effects, not about wall-clock time. "A happens-before B" means: everything A did is visible to B, and B sees A's writes in the order A made them.
The rules you use are short:
- Program order: within one thread, each action happens-before the next.
- Monitor: unlock of a monitor happens-before every later lock of it.
- Volatile: a write to a volatile field happens-before every later read of it.
- Thread start and join:
start()happens-before the first action of the thread, and the last action of a thread happens-beforejoin()returning.
Without such an edge between two threads, you get no promise at all. E3 Q169 lists the rules, and E2 The Java Memory Model gives the full model.
- "Why does a locking reader in the demo escape the loop?"
-
Each call to
isReady()locks and then unlocks the monitor. Taking the lock forces the reading thread to see the writes published by the earlier unlock, so after the writer'ssetReady()the next lock seestrue.In the machine's terms, entering a synchronized block is an acquire and leaving it is a release. The compiler cannot hoist a read across an acquire, so the loop must re-read.
The effect resembles the volatile fix from Q66, with the lock doing the work. In real code I would prefer
volatilefor a plain flag, since a lock per spin is heavier than needed.The point of the demo is the pair. Writer and reader must agree on one lock, and the guarantee only travels along that shared lock.
- "Is it safe to read without the lock if I only write under the lock?"
-
Not for general state. The unlocked read may see a stale value, or in a multi-field object a mix of old and new values (field A already updated, field B not).
There are narrow safe cases. The field is
volatile, so the read is ordered by volatile instead. Or the field isfinalin an immutable object that was published safely. Or the value is a singleintorbooleanwhere a stale read is genuinely harmless and you have documented that.The common bug is a "fast path" that skips the lock for reads of a counter or a map size, and returns impossible numbers under load.
The simple rule I follow: guard every access, reads included, or make the variable volatile, atomic or immutable. A comment such as "guarded by this" next to each field helps reviewers check it.
Q69 · Scenario. "Two threads deadlock while transferring money between two accounts. Show the fix."
Reveal answer
Strong answer The classic cause is lock ordering. transfer(a, b) locks a first and then b. At the same moment transfer(b, a) locks b first and then a. Each thread holds one lock and waits for the one the other holds, and neither can ever continue.
A deadlock needs four conditions to hold together: mutual exclusion (only one holder), hold and wait (a thread holds one lock while asking for another), no preemption (nobody can take a lock away) and a circular wait (A waits for B, B waits for A). You break a deadlock by breaking one of them. In practice you break the circle.
The fix is a global lock order. Every thread must take locks in the same order, whatever the call looks like. For accounts, order by a unique, stable key such as the account id: always lock the lower id first. Then transfer(a, b) and transfer(b, a) both lock the same account first, so one simply waits for the other.
The code is short: pick first = from.id < to.id ? from : to and second as the other, then synchronized (first) { synchronized (second) { ... } }. The debit and credit still use from and to inside.
When there is no natural key, use System.identityHashCode with a tie-breaker lock for the rare equal case. Another option is tryLock(timeout) on both locks with a back-off and retry, which turns a permanent hang into a failed attempt you can retry (Q81).
The primer builds both fixes in Synchronization as Lock ordering and tryLock with timeout. E3 Q174 lists the four conditions and Q175 is the 2 a.m. production freeze.
Picture it The broken transfer and the fixed one, run with the same two accounts.
The setup: Two accounts with 1,000 each. One thread moves 100 from account 1 to 2, another moves 50 from 2 to 1. A 100 ms pause between the two locks makes the clash reliable. The broken program runs under timeout 5.
public class Q69Deadlock {
static class Account {
final int id; int balance;
Account(int id, int balance) { this.id = id; this.balance = balance; }
}
static void transfer(Account from, Account to, int amt) {
synchronized (from) {
pause(); // widen the window so the demo is reliable
synchronized (to) { from.balance -= amt; to.balance += amt; }
}
}
static void pause() { try { Thread.sleep(100); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
Account a = new Account(1, 1000), b = new Account(2, 1000);
Thread t1 = new Thread(() -> transfer(a, b, 100), "A-to-B");
Thread t2 = new Thread(() -> transfer(b, a, 50), "B-to-A");
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("done: " + a.balance + " / " + b.balance);
}
}Make the invisible visible: Run it under timeout 5 and take a thread dump while it hangs (jstack <pid>).
$ timeout 5 java Q69Deadlock.java ; echo "exit=$?"
exit=124 (no "done" line: it hung until timeout killed it)Found one Java-level deadlock:
=============================
"A-to-B":
waiting to lock monitor 0x00007502a0001110 (object 0x0000000092963cc0, a Q69Deadlock$Account),
which is held by "B-to-A"
"B-to-A":
waiting to lock monitor 0x00007502a4001190 (object 0x0000000092963ca8, a Q69Deadlock$Account),
which is held by "A-to-B"
Java stack information for the threads listed above:
===================================================
"A-to-B":
at Q69Deadlock.transfer(Q69Deadlock.java:9)
- waiting to lock <0x0000000092963cc0> (a Q69Deadlock$Account)
- locked <0x0000000092963ca8> (a Q69Deadlock$Account)
at Q69Deadlock.lambda$main$0(Q69Deadlock.java:15)
at Q69Deadlock$$Lambda/0x0000000022158420.run(Unknown Source)
at java.lang.Thread.runWith(java.base@25.0.5.1/Thread.java:1487)
at java.lang.Thread.run(java.base@25.0.5.1/Thread.java:1474)
"B-to-A":
at Q69Deadlock.transfer(Q69Deadlock.java:9)
- waiting to lock <0x0000000092963ca8> (a Q69Deadlock$Account)
- locked <0x0000000092963cc0> (a Q69Deadlock$Account)
at Q69Deadlock.lambda$main$1(Q69Deadlock.java:16)
at Q69Deadlock$$Lambda/0x0000000022159800.run(Unknown Source)
at java.lang.Thread.runWith(java.base@25.0.5.1/Thread.java:1487)
at java.lang.Thread.run(java.base@25.0.5.1/Thread.java:1474)
Found 1 deadlock.What you see: The program never printed "done". The JVM itself reports "Found one Java-level deadlock": A-to-B holds account 0x...ca8 and waits for 0x...cc0, while B-to-A holds cc0 and waits for ca8. That is the circle.
The fix: Lock the lower account id first, in both directions.
public class Q69DeadlockFixed {
static class Account {
final int id; int balance;
Account(int id, int balance) { this.id = id; this.balance = balance; }
}
static void transfer(Account from, Account to, int amt) {
Account first = from.id < to.id ? from : to; // always lock the lower id first
Account second = from.id < to.id ? to : from;
synchronized (first) {
pause();
synchronized (second) { from.balance -= amt; to.balance += amt; }
}
}
static void pause() { try { Thread.sleep(100); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
Account a = new Account(1, 1000), b = new Account(2, 1000);
Thread t1 = new Thread(() -> transfer(a, b, 100), "A-to-B");
Thread t2 = new Thread(() -> transfer(b, a, 50), "B-to-A");
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("done: " + a.balance + " / " + b.balance + " total " + (a.balance + b.balance));
}
}done: 950 / 1050 total 2000Why: Both threads now try account 1 first. One wins, finishes its transfer, and releases both. The other then proceeds. The balances are 950 and 1,050 and the total stays 2,000.
Locks in call order
Opposite calls take the locks in opposite order.
synchronized (from) {
synchronized (to) {
from.balance -= amt;
to.balance += amt;
}
} // a to b, b to a: circular waitLocks in id order
Both calls lock the lower id first. No circle.
Account a = from.id < to.id ? from : to;
Account b = from.id < to.id ? to : from;
synchronized (a) {
synchronized (b) { /* debit, credit */ }
}The shift: The fix does not remove a lock, it removes the circle, by making every thread ask in the same order.
Land it I break the circular wait with one global lock order, usually by account id, and I add a tryLock timeout where an order is hard to define.
- "What if the two accounts have the same id, for example transfer(a, a)?"
-
Then
from.id < to.idis false, both variables point at the same object, and the code locks it twice.synchronizedis reentrant (a thread that holds a monitor may take it again), so this does not deadlock. The debit and credit net to zero.The wider issue is ties between different objects with equal keys. If two different objects could have the same id, the order of the two locks is undefined and the circle is back. Then you need a tie-breaker, for example a global "tie lock" taken first when the keys are equal.
With a database, the problem moves: you order the row locks, by
SELECT ... ORDER BY id FOR UPDATE, and the database detects and aborts a deadlock for you. E8 covers this on the database side.My practice is to assert in the transfer method that
from != toor to short-circuit it, and to keep keys unique by construction. - "Can tryLock with a timeout replace the ordering?"
-
It replaces the permanent hang with a failed attempt, which is often enough. A thread takes the first lock, then tries
second.tryLock(50, ms). If it fails, it releases the first lock, waits a random short time and retries. No thread can hold a lock forever while waiting.The cost is a new failure mode, livelock: two threads that keep backing off and retrying in step and still make no progress (E3 Q176). A random delay in the back-off breaks the pattern.
I use ordering when a natural order exists (ids, resource names), because it needs no retries and no timeouts. I use
tryLockwhen the locks come from different modules and no shared order exists, or when a lock may be held for a long time and I prefer to fail fast.The primer runs the
tryLock(1, SECONDS)demo: the second thread gives up after one second instead of hanging. - "Why did the program not just crash with an exception?"
-
Because a deadlock is not an error the JVM treats as one. Two threads are waiting for monitors, which is a legal state. The JVM does not kill either thread. The process stays alive, uses no CPU, and appears to hang.
That is what makes it hard in production. There is no stack trace in the log, no error metric, only requests that never finish and a thread pool that slowly fills with BLOCKED threads.
The JVM can report it on request. A thread dump (
jstack,jcmd Thread.Print, orkill -3) prints "Found one Java-level deadlock" with the threads and monitors, as above. Q70 covers detection from inside the program and from outside.Databases are different: they detect deadlocks and abort one transaction for you. The JVM's own monitors are not that kind.
- "How do I stop this from reaching production?"
-
Three layers, from cheap to expensive.
- Design: avoid holding two locks. Make the unit of locking larger (one lock for the whole bank) or smaller (one lock, one account, no nested calls), or use immutable data and message queues.
- Review rules: never call unknown code (callbacks, listeners, overridable methods) while holding a lock, and document the lock order next to the locks.
- Detection: a monitor thread that calls
ThreadMXBean.findDeadlockedThreads()every few seconds and raises an alert (Q70), plus tests that run the contended paths with many threads under a timeout.
The timeout is the key detail in tests. A deadlock test without a timeout hangs the CI build, and the demo above ran under
timeout 5for the same reason.
Q70. "How do you find a deadlock in a running JVM?"
Reveal answer
Strong answer There are two ways, and they answer the same question. Ask the JVM from the outside with a thread dump, or ask it from the inside with ThreadMXBean. Both use the same detector, which looks for a cycle in the "thread waits for monitor held by thread" graph.
From the outside, take a dump while the process is stuck: jstack <pid>, or jcmd <pid> Thread.print, or send kill -3 <pid> and read the output in the process's console or log. At the bottom of the dump the JVM prints "Found one Java-level deadlock" with each thread, the monitor it waits for and the thread that holds it.
Without that banner, read the dump by hand. Look for several threads in state BLOCKED on a monitor address, and follow each "waiting to lock <0x...>" to the thread that shows "locked <0x...>". A closed loop is a deadlock. Take two dumps a few seconds apart. Threads that stay in the same place are stuck, not just busy.
From the inside, ManagementFactory.getThreadMXBean().findDeadlockedThreads() returns the ids of deadlocked threads (or null). It covers synchronized monitors and java.util.concurrent locks (use findDeadlockedThreads, not the older findMonitorDeadlockedThreads). A scheduled health check that calls it can alert on the first deadlock.
Not every hang is a deadlock. A thread stuck on one lock whose owner is waiting on the network, a full queue, or a thread waiting forever for a signal are all hangs the detector does not call deadlocks. For those the dump still shows who waits for what.
The primer shows the dump in Synchronization. E3 Q175 walks the 2 a.m. freeze and Q201 handles the case where the owner is idle, not blocked.
Picture it A tiny program that detects its own deadlock.
The setup: Two daemon threads, "kitchen" and "billing", take two locks in opposite order. After 500 ms main asks ThreadMXBean for deadlocked threads and prints who waits for whom.
import java.lang.management.*;
public class Q70FindDeadlock {
static final Object A = new Object(), B = new Object();
static void grab(Object first, Object second) {
synchronized (first) {
try { Thread.sleep(100); } catch (InterruptedException e) { }
synchronized (second) { }
}
}
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(() -> grab(A, B), "kitchen");
Thread t2 = new Thread(() -> grab(B, A), "billing");
t1.setDaemon(true); t2.setDaemon(true);
t1.start(); t2.start();
Thread.sleep(500);
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
long[] ids = mx.findDeadlockedThreads();
System.out.println("deadlocked thread count: " + (ids == null ? 0 : ids.length));
for (ThreadInfo ti : mx.getThreadInfo(ids)) {
System.out.println(ti.getThreadName() + " is " + ti.getThreadState() + ", waiting for a lock held by " + ti.getLockOwnerName());
}
}
}Make the invisible visible: Run it.
deadlocked thread count: 2
kitchen is BLOCKED, waiting for a lock held by billing
billing is BLOCKED, waiting for a lock held by kitchenWhat you see: Two threads, both BLOCKED, each waiting for a lock the other owns. The detector names the owner of each lock.
Why: The same data fills the jstack banner you saw in Q69. The MXBean is the programmatic version, so a service can check itself on a timer. I made the threads daemons so the demo exits after the report.
Make the invisible visible: From outside the process, the commands are:
$ jps -l # find the pid
$ jstack <pid> | grep -A 12 "deadlock"
$ jcmd <pid> Thread.print # same data, via jcmd
$ kill -3 <pid> # dump goes to the process's stdoutLand it I find deadlocks with jstack or jcmd Thread.print from outside and findDeadlockedThreads() from inside, and I read the BLOCKED threads as a graph.
- "What if the dump does not say Found one Java-level deadlock but the service is still stuck?"
-
Then it is another kind of hang, and the dump is still the evidence. Check for four common shapes.
- Everyone waits on one lock: many threads BLOCKED on the same address, one thread that "locked" it and is itself waiting on I/O or sleeping. That is lock contention with a slow owner (E3 Q201).
- Pool starvation: all pool threads are WAITING in
Future.get(), waiting for tasks queued in the same pool. This is a thread-starvation deadlock, not a monitor deadlock, so the detector does not see it. - Lost signal: a thread WAITING in
wait()for a notify that already happened (E3 Q163). - Everything waits on a downstream call: threads in socket reads with no timeout.
I count threads by state and top frame first. That summary usually tells me which of the four it is in under a minute.
- "Does findDeadlockedThreads see ReentrantLock deadlocks?"
-
Yes, if you call the right method.
findDeadlockedThreads()detects cycles through bothsynchronizedmonitors and the ownable synchronizers behindReentrantLockandReentrantReadWriteLock. The olderfindMonitorDeadlockedThreads()covers monitors only.It does not see locks that are not ownable: a
SemaphoreorCountDownLatchhas no owner thread, so a deadlock formed with them is invisible to the detector.The dump from
jstackshowsjava.util.concurrentlocks too, as "parking to wait for <0x...> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)",. Thejcmd <pid> Thread.print -loption also prints the owned synchronizers.When I use
ReentrantLockI name the lock-holding code paths clearly, because a plain dump alone may need the-lflag to show who owns what. - "How can I get thread dumps automatically when the service hangs?"
-
Make it a habit of the platform, not a heroic act at 2 a.m. Four options.
- Actuator: Spring Boot exposes
/actuator/threaddump, so a script or an alert hook can fetch it (E4). - Self-check: the
ThreadMXBeanloop from the demo, running every 10 seconds, that logs the full thread dump when it finds a deadlock. - Kubernetes hook: a liveness failure handler that runs
jcmd Thread.printbefore the pod is killed. - JFR: Java Flight Recorder, always on at low overhead, records lock contention and thread states you can inspect later.
Whichever you pick, take two dumps five seconds apart. One dump shows a state, two dumps show whether it is changing.
- Actuator: Spring Boot exposes
- "Can I just avoid deadlocks by using only java.util.concurrent classes?"
-
It lowers the risk a lot but does not remove it. Concurrent collections, atomics, and queues do their locking internally in a fixed, tested way, so you cannot create a lock-order bug inside them.
You can still deadlock around them. A task waits for another task's result in the same bounded pool. A
computeIfAbsentfunction that touches the same map can hang (Q83). TwoCountDownLatches that wait for each other never open.The strongest protection is a design with no nested waiting: tasks that do not block on other tasks of the same pool, one lock held at a time, and message passing between components. Immutable data cuts out many locks altogether.
So I treat
java.util.concurrentas a safer starting point, and the thread dump as the tool that tells me when I was wrong.
These questions move from raw threads to pools. They test whether you know what a pool does with a task, where tasks wait, how failures travel, and how to stop the whole thing cleanly.
Q71. "Why use an ExecutorService instead of new Thread()?"
Reveal answer
Strong answer Because a thread is expensive and a task is cheap, and an executor separates the two. new Thread() ties one task to one operating-system thread, which costs about a megabyte of stack address space and a measurable time to create. An ExecutorService keeps a small set of worker threads alive and feeds them tasks, so the thread cost is paid once.
The second benefit is control. A pool has a maximum size, so a burst of 20,000 tasks cannot create 20,000 threads and crash the process. Extra tasks wait in a queue, or are rejected by a policy you choose (Q75).
The third is results and failures. submit returns a Future, so the caller gets the value or the exception (Q72, Q73). A raw thread offers neither.
The fourth is lifecycle. shutdown, awaitTermination and, since Java 19, close() stop the workers cleanly (Q77). Raw threads need hand-written bookkeeping, and a forgotten non-daemon thread keeps the JVM alive.
The fifth is naming and monitoring. A thread factory gives workers meaningful names (Q79), and the pool exposes queue size and active count for metrics.
The price is that you must now size the pool and choose its queue, and those choices cause the production bugs in Q76. For blocking I/O with many concurrent calls, Java 21 virtual threads change the trade-off: you can use one cheap thread per task, with no pool sizing (Q94, Q95).
The primer builds this from the OutOfMemoryError incident in Executors. E3 Q181 asks the same question in interview form.
Picture it The cost of 10,000 raw threads against 10,000 tasks on 16 workers.
The setup: Each task is one counter increment. First, 10,000 new Thread objects are started and joined. Then 10,000 tasks go to a 16-thread pool inside try-with-resources. Finally the worker names are counted.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q71PoolVsThreads {
public static void main(String[] args) throws Exception {
int n = 10_000;
AtomicInteger done = new AtomicInteger();
long t0 = System.nanoTime();
Thread[] ts = new Thread[n];
for (int i = 0; i < n; i++) { ts[i] = new Thread(done::incrementAndGet); ts[i].start(); }
for (Thread t : ts) t.join();
System.out.println("10,000 new Thread(): " + (System.nanoTime() - t0) / 1_000_000 + " ms, done=" + done);
done.set(0);
t0 = System.nanoTime();
try (ExecutorService pool = Executors.newFixedThreadPool(16)) {
for (int i = 0; i < n; i++) pool.submit(done::incrementAndGet);
}
System.out.println("10,000 tasks, 16-thread pool: " + (System.nanoTime() - t0) / 1_000_000 + " ms, done=" + done);
// threads actually used
ConcurrentHashMap<String, Integer> names = new ConcurrentHashMap<>();
try (ExecutorService pool = Executors.newFixedThreadPool(16)) {
for (int i = 0; i < n; i++) pool.submit(() -> names.merge(Thread.currentThread().getName(), 1, Integer::sum));
}
System.out.println("distinct worker threads used: " + names.size());
}
}Make the invisible visible: Time both, and count the distinct threads the pool used.
10,000 new Thread(): 1337 ms, done=10000
10,000 tasks, 16-thread pool: 42 ms, done=10000
distinct worker threads used: 16What you see: 10,000 threads took 1,337 ms. The same 10,000 tasks on 16 workers took 42 ms, about 30 times faster, and exactly 16 threads did all the work.
Why: The pool paid for 16 threads and reused them. The raw version paid 10,000 times, and at that rate a real service would hit the operating system's thread limit (the OutOfMemoryError: unable to create native thread of the primer's incident). I did not try to exhaust the limit. Timings are from this machine and will differ.
new Thread per task
One thread per task. Cost and count grow with the load.
for (Order o : orders) {
new Thread(() -> notify(o)).start();
}
// 20,000 orders -> 20,000 threads
// no result, no limit, no namesExecutorService
A few reused workers, a queue, and a Future per task.
try (var pool =
Executors.newFixedThreadPool(16)) {
for (Order o : orders)
pool.submit(() -> notify(o));
} // close() waits for the tasksThe shift: The executor makes the number of threads a setting you choose, not a side effect of the load.
Land it I use an executor because it bounds the thread count, reuses workers, returns Futures and gives me a clean shutdown, none of which raw threads offer.
- "Why is creating a thread so expensive?"
-
A platform thread is a real operating-system thread. Creating one asks the kernel for a thread structure, and the JVM reserves a stack for it, 1 MB of address space by default on 64-bit Linux (the
-Xsssetting). Starting it means a system call and scheduler work.The cost has two parts. The one-off cost is creation: in the run above, about 0.13 ms per thread. The running cost is memory and scheduling: thousands of runnable threads increase context switches, and each blocked thread still holds its stack.
The hard limit is the operating system's thread count and the memory for stacks. When it is reached,
Thread.start()throwsOutOfMemoryError: unable to create native thread, which is a native resource error, not a heap error.Virtual threads (Java 21) remove most of this cost by being ordinary Java objects scheduled on a few carrier threads. Q94 shows 100,000 of them created in a second.
- "How many threads should a pool have?"
-
It depends on the work, and the answer is a formula with a measurement behind it. For CPU-bound tasks (computation, no waiting), use about the number of cores, or cores plus one. More threads only add context switching. On this 12-core machine that is 12.
For I/O-bound tasks (waiting on a database or network), threads spend most of their time idle, so you can have more. A rule of thumb is cores times (1 + wait time / compute time). If a task waits 200 ms and computes 20 ms, that is 12 times 11, about 130 threads.
Then measure. Watch throughput and latency as you change the size, and remember the downstream limit: 130 threads calling a database with 20 connections just moves the queue.
For I/O with huge fan-out, I would not size a pool at all in Java 21 or later. I would use virtual threads and put a
Semaphorein front of the fragile resource (Q80). E3 Q184 gives the full sizing method with numbers. - "What do the Executors factory methods give me, and which should I avoid?"
-
The factory class offers four common shapes:
Factory Shape Catch newFixedThreadPool(n)n workers, unbounded queue Queue can grow until memory runs out (Q76) newCachedThreadPool()Grows with demand, no queue Unbounded thread count under a burst newSingleThreadExecutor()One worker, unbounded queue Same queue risk; good for ordering newScheduledThreadPool(n)Delayed and periodic tasks A throwing periodic task stops silently (Q78) Each hides an unbounded something. For production services I build a
ThreadPoolExecutorby hand with a bounded queue, a named thread factory and a rejection policy, as in the primer's Bounded pool. - "Is an executor always better than creating a thread?"
-
For repeated or many tasks, yes. For one long-lived background loop, a dedicated thread is fine and simpler: a heartbeat sender, a file watcher, a consumer loop. There the thread is not a task, it is a service component with its own lifecycle.
Even then I prefer to create it through
Thread.ofPlatform().name("heartbeat").daemon().start(...)(Java 21) or a thread factory, so that it has a name, a daemon flag and an uncaught-exception handler set on purpose.The real rule is not "executors, never threads". It is "never create threads in a loop that depends on the load". Any code path whose thread count follows request volume needs a bounded pool or virtual threads.
E3 Q142 discusses
Runnableversus subclassingThread, which is the neighbouring question.
Q72. "submit versus execute — and what happens to an exception in each?"
Reveal answer
The real test Whether you know that submit captures an exception in the Future and shows it only on get(). Ignoring the returned Future makes the failure silent.
Strong answer execute(Runnable) is the basic method from the Executor interface. It runs a Runnable, returns void, and gives you nothing back. submit(...) comes from ExecutorService and takes a Runnable or a Callable. It returns a Future.
The difference shows up when the task throws. With execute, the exception leaves the worker thread's run method, so the thread's uncaught exception handler runs, and the default prints the stack trace to standard error. The pool then replaces that worker with a new thread.
With submit, the wrapper (a FutureTask) catches the exception and stores it inside the Future. Nothing is printed. The exception comes out only when someone calls future.get(), as an ExecutionException whose cause is the original.
That makes submit the more dangerous method for fire-and-forget work. If you ignore the returned future, the failure vanishes: no log, no metric, no retry. The classic bug is pool.submit(() -> process(order)) in a loop, with failures nobody ever sees.
Rules that keep it safe: use execute (or a handler) for fire-and-forget and let the uncaught handler log, or wrap the body in your own try/catch that logs. Use submit only when you will call get(), or attach the future to something that checks it.
The same problem returns in CompletableFuture (Q92). E3 Q182 shows the path a task takes through the pool, and Q188 shows a related silent failure.
Picture it The same failing task sent through both methods.
The setup: A 2-thread pool. First an execute call throws an IllegalStateException. Then a submit call throws one. After each, the program waits 300 ms and checks what was printed and what the future holds.
import java.util.concurrent.*;
public class Q72SubmitExecute {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
System.out.println("--- execute: the exception goes to the thread's uncaught handler");
pool.execute(() -> { throw new IllegalStateException("boom from execute"); });
Thread.sleep(300);
System.out.println("--- submit: the exception is stored in the Future; nothing printed yet");
Future<?> f = pool.submit(() -> { throw new IllegalStateException("boom from submit"); });
Thread.sleep(300);
System.out.println("future.isDone() = " + f.isDone());
try { f.get(); } catch (ExecutionException e) { System.out.println("get() threw: " + e.getClass().getSimpleName() + " caused by " + e.getCause()); }
pool.shutdown();
}
}Make the invisible visible: Run it and read what each path printed.
--- execute: the exception goes to the thread's uncaught handler
Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: boom from execute
at Q72SubmitExecute.lambda$main$0(Q72SubmitExecute.java:7)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)
at java.base/java.lang.Thread.run(Thread.java:1474)
--- submit: the exception is stored in the Future; nothing printed yet
future.isDone() = true
get() threw: ExecutionException caused by java.lang.IllegalStateException: boom from submitWhat you see: The execute failure printed a full stack trace under the thread name pool-1-thread-1. The submit failure printed nothing at all. The future was already done, and the exception only appeared when get() was called.
Why: submit wrapped the task and captured the throwable. If the main thread had not called get(), the trace would have been lost for good.
execute — loud
The exception reaches the thread's uncaught handler and is printed.
pool.execute(() -> {
throw new IllegalStateException("boom");
});
// stderr: Exception in thread
// "pool-1-thread-1" ...boomsubmit — quiet until get()
The exception waits inside the Future.
Future<?> f = pool.submit(() -> {
throw new IllegalStateException("boom");
});
// nothing printed ...
f.get(); // ExecutionExceptionThe shift: execute reports a failure at once, while submit keeps it until somebody asks.
Land it I treat submit as "the failure waits in the future", so I either call get() or catch and log inside the task.
- "How do I log exceptions from submitted tasks that nobody reads?"
-
Three options, from simplest to most general.
- Catch inside the task: wrap the body in try/catch and log with context (order id, user). It is explicit and works for
execute,submitand scheduled tasks. - Wrap the executor: a decorator that wraps every
Runnablein one that catches and logs. All callers are covered, with a single place to add metrics. - Override
afterExecute: in aThreadPoolExecutorsubclass, the hook receives the throwable forexecute, and forsubmityou must unwrap theFutureto see it.
I use option 1 in application code and option 2 in a shared platform library, so teams do not each invent their own.
- Catch inside the task: wrap the body in try/catch and log with context (order id, user). It is explicit and works for
- "What happens to the worker thread when a task throws?"
-
It depends on the method. With
executethe exception escapes the worker loop, the worker thread dies, and the pool starts a replacement the next time it needs one. You can see this in logs as thread numbers that keep increasing (pool-1-thread-1, thenpool-1-thread-3) when some tasks fail.With
submitthe exception is caught by theFutureTask, so the worker survives and takes the next task. That is an efficiency advantage and a visibility disadvantage.The replacement costs a thread creation, which is cheap in occasional failures but real if every task fails (for example when a downstream is down). Then a stream of dying and spawning threads adds load while the service is already unhealthy.
Either way, the pool itself stays correct. A throwing task does not poison the pool, which is why tasks must handle their own errors.
- "What does the Future hold if the task was cancelled?"
-
A cancelled future behaves differently from a failed one.
future.cancel(true)marks it cancelled. A laterget()throwsCancellationException, which is unchecked, notExecutionException.isCancelled()andisDone()both return true.The
trueargument means "interrupt the worker if the task is already running". The task only stops early if it responds to interruption, for example by being insleepor a blocking queue call, or by checkingisInterrupted(). A tight CPU loop that never checks keeps running to the end (E3 Q195).Q73 shows these three outcomes side by side: a value, a timeout, and an exception. The summary: normal completion gives a value, failure gives
ExecutionException, cancellation givesCancellationException. - "Why do some libraries use execute and others submit?"
-
Because of what they promise the caller. A library that returns results (a client that fetches many things) uses
submitso it can hand back futures. A library that runs callbacks or listeners and does not care about a result usesexecute, and often wraps the callback with its own error handling.Some libraries use
executedeliberately to keep the default "print to stderr" behaviour for unexpected errors, because it makes bugs visible during development.The rule for my own code: if I return or store the
Future,submitis right. If I fire and forget, I either useexecutewith a body that logs, or I usesubmitand attach a completion check. What I never do issubmitand drop the future without a try/catch inside the task.
Q73. "Future.get(): blocking, timeouts and ExecutionException."
Reveal answer
Strong answer future.get() is how you collect the result of a submitted task. It blocks: the calling thread waits until the task finishes. It then returns the value, throws ExecutionException if the task failed, throws CancellationException if it was cancelled, or throws InterruptedException if the waiting thread was interrupted.
get(timeout, unit) waits at most that long. If time runs out it throws TimeoutException, and importantly the task keeps running. A timeout only stops waiting. To stop the work you must call future.cancel(true) yourself.
ExecutionException is a wrapper. The real failure is its cause: e.getCause(). The wrapper exists because the exception happened on another thread, and Java must tell you that apart from a failure of get() itself. A typical handler unwraps the cause, rethrows runtime exceptions, and logs or translates the rest.
Blocking has consequences. A request thread that calls get() without a timeout can wait forever if the task is stuck, and a pool whose tasks wait for other tasks of the same pool can deadlock by starvation. Always use a timeout in service code, and never call get() from a pool thread on a task queued to the same pool.
Other useful calls: isDone() (finished any way), resultNow() and exceptionNow() (Java 19, for a future you know is done), and state() (Java 19) to inspect without throwing.
Plain futures are limited, and CompletableFuture exists to fix that (Q87). E3 Q189 lists the limits, and Q195 explains why cancel(true) sometimes does not stop the work.
Picture it Every way a get() can end, in one program.
The setup: A 2-thread pool. A task takes 300 ms and succeeds. A second takes 2,000 ms, is waited for 300 ms, then cancelled. A third takes 50 ms and throws. Elapsed times are printed.
import java.util.concurrent.*;
public class Q73FutureGet {
static String slowMenu(int ms, boolean fail) throws Exception {
Thread.sleep(ms);
if (fail) throw new IllegalArgumentException("restaurant closed");
return "menu";
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
long t0 = System.nanoTime();
Future<String> f = pool.submit(() -> slowMenu(300, false));
System.out.println("submit returned after " + (System.nanoTime() - t0) / 1_000_000 + " ms");
System.out.println("get() -> " + f.get() + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms");
Future<String> slow = pool.submit(() -> slowMenu(2000, false));
try { slow.get(300, TimeUnit.MILLISECONDS); }
catch (TimeoutException e) { System.out.println("get(300 ms) -> " + e.getClass().getSimpleName() + ", task still running: " + !slow.isDone()); }
System.out.println("cancel(true) -> " + slow.cancel(true) + ", isCancelled=" + slow.isCancelled());
try { slow.get(); } catch (CancellationException e) { System.out.println("get() after cancel -> CancellationException"); }
Future<String> bad = pool.submit(() -> slowMenu(50, true));
try { bad.get(); }
catch (ExecutionException e) { System.out.println("get() -> ExecutionException: " + e.getMessage() + "\n cause = " + e.getCause()); }
pool.shutdown();
}
}Make the invisible visible: Run it.
submit returned after 1 ms
get() -> menu after 303 ms
get(300 ms) -> TimeoutException, task still running: true
cancel(true) -> true, isCancelled=true
get() after cancel -> CancellationException
get() -> ExecutionException: java.lang.IllegalArgumentException: restaurant closed
cause = java.lang.IllegalArgumentException: restaurant closedWhat you see: submit returned after 1 ms, and get() blocked for 303 ms. The 300 ms timeout threw TimeoutException while the task was still running. cancel(true) then stopped it, and a later get() threw CancellationException. The failing task gave an ExecutionException whose cause is the original exception.
Why: The future is a receipt for work happening elsewhere. Each outcome has its own signal, so a caller can tell success, slowness, cancellation and failure apart.
get() with no limit
Waits as long as the task takes. A stuck task stalls the caller.
Future<String> f = pool.submit(task);
String menu = f.get();
// request thread parked, maybe foreverget() with a limit and cleanup
Gives up after a deadline and cancels the work.
try {
menu = f.get(300, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
f.cancel(true); // stop the work too
menu = cachedMenu;
}The shift: A timeout turns "wait for the task" into "wait this long, then do something else".
Land it I never call get() without a timeout in service code, I unwrap ExecutionException to its cause, and I cancel the task when I give up.
- "Why is it ExecutionException and not the original exception?"
-
Because the original was thrown on a different thread, and
get()has its own ways to fail that must stay distinguishable. Ifget()rethrew anIOExceptionfrom the task, you could not tell "the task's I/O failed" from "waiting was interrupted".The wrapper also preserves the task thread's stack trace as the cause, so the trace shows where the real failure happened. The
ExecutionException's own trace shows whereget()was called.A small helper keeps call sites tidy: catch
ExecutionException, checkgetCause(), rethrowRuntimeExceptionorErroras they are, and wrap checked ones in your own domain exception.CompletableFuture.join()uses a different wrapper,CompletionException(Q93). - "Does a get() timeout stop the task?"
-
No, and this surprises people.
TimeoutExceptionmeans "I stopped waiting". The task is still running on its worker, still using the CPU, and will finish later with a result nobody reads.In the demo, after the timeout the task was still running (
!slow.isDone()printed true) untilcancel(true)was called.That leak matters under load. A service that times out requests but never cancels the work accumulates abandoned tasks until the pool is full of work nobody wants.
So the pattern is always:
get(timeout), catchTimeoutException,cancel(true), then fall back. And the task must respond to interruption for the cancel to have an effect, which E3 Q195 covers. - "How do I wait for many futures?"
-
You have four choices, and they differ in who waits.
- Loop over
get(): total wait is the longest task, because the tasks run in parallel while you wait in order. Simple, but one failure surfaces only when you reach it. invokeAll: submits a list of callables and returns when all are done (Q74).ExecutorCompletionService: gives results in completion order, so you can handle the fastest first.CompletableFuture.allOf: composes without blocking (Q91).
For simple batches I use
invokeAllwith a timeout, and for pipelines I useCompletableFuture. - Loop over
- "What are resultNow() and state() for?"
-
They arrived in Java 19.
state()returns an enum (RUNNING, SUCCESS, FAILED, CANCELLED) without blocking or throwing, so you can inspect a future safely, for example in a status endpoint.resultNow()returns the value of a future you know has succeeded, and throwsIllegalStateExceptionif it is not done or failed.exceptionNow()returns the failure. Both avoid theget()try/catch when you have already checked completion, as you do afterinvokeAllor in awhenCompletecallback.They make the common loop shorter: after
invokeAll, every future is done, sof.resultNow()is safe for the successful ones.I checked with
javap: they are present on JDK 25 and absent on JDK 17, so check your target release.
Q74. "invokeAll versus invokeAny."
Reveal answer
Strong answer Both take a collection of Callables and run them on the pool. They differ in what you wait for and what you get back.
invokeAll waits for every task to finish and returns a List<Future>, in the same order as the input. Each future is already done, so get() returns at once, or throws if that task failed. Use it when you need all the answers: price, menu and rider ETA for a checkout.
invokeAny returns the result of one task that completed successfully, and cancels the rest. It does not return a future, only the value. If some tasks fail it ignores them and waits for one that succeeds. Only if all of them fail does it throw ExecutionException. Use it for redundancy: ask three replicas, take the first good answer.
Total time is the clear difference. For three QuickBite services of 300, 250 and 350 ms, doing them one after another takes about 900 ms. invokeAll on a pool with at least three threads takes about the slowest one, 350 ms. invokeAny takes about the fastest, 250 ms.
Both have timeout versions, invokeAll(tasks, timeout, unit) and invokeAny(tasks, timeout, unit). With invokeAll, tasks not finished by the deadline are cancelled and their futures report cancelled, so check isCancelled().
Two cautions. The pool needs enough threads: with a pool of 1, invokeAll is sequential. And both block the caller, which is fine for a request thread with a timeout but not for an event loop.
For anything richer (combine two results into a record, fall back per call) use CompletableFuture (Q91). E3 has no separate question for these two methods, but Q182 shows the pool path they feed.
Picture it The three QuickBite services, run three ways.
The setup: menu sleeps 300 ms, price 250 ms and riderEta 350 ms. They run in a row, then through invokeAll, then through invokeAny. A last call mixes a failing task with a good one.
import java.util.*;
import java.util.concurrent.*;
public class Q74InvokeAllAny {
static Callable<String> svc(String name, int ms) { return () -> { Thread.sleep(ms); return name; }; }
public static void main(String[] args) throws Exception {
List<Callable<String>> calls = List.of(svc("menu", 300), svc("price", 250), svc("riderEta", 350));
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
long t0 = System.nanoTime();
for (Callable<String> c : calls) c.call();
System.out.println("sequential: " + (System.nanoTime() - t0) / 1_000_000 + " ms");
t0 = System.nanoTime();
List<Future<String>> all = pool.invokeAll(calls);
StringBuilder sb = new StringBuilder();
for (Future<String> f : all) sb.append(f.get()).append(' ');
System.out.println("invokeAll: " + (System.nanoTime() - t0) / 1_000_000 + " ms -> " + sb);
t0 = System.nanoTime();
String first = pool.invokeAny(calls);
System.out.println("invokeAny: " + (System.nanoTime() - t0) / 1_000_000 + " ms -> first winner " + first);
List<Callable<String>> mixed = List.of(
() -> { throw new RuntimeException("cache miss"); }, svc("database", 200));
System.out.println("invokeAny with one failing: " + pool.invokeAny(mixed));
}
}
}Make the invisible visible: Run it.
sequential: 900 ms
invokeAll: 352 ms -> menu price riderEta
invokeAny: 251 ms -> first winner price
invokeAny with one failing: databaseWhat you see: Sequential took 900 ms, invokeAll 352 ms (the slowest task), and invokeAny 251 ms with price, the fastest, as winner. With one task failing, invokeAny ignored it and returned database.
Why: invokeAll is a barrier over all tasks, invokeAny is a race that cancels the losers. In the last case the failure was swallowed by design: only "no task succeeded" is an error.
Wait one by one
The three calls add up to 900 ms.
String menu = menu(); // 300 ms
int price = price(); // 250 ms
String eta = riderEta(); // 350 ms
// total about 900 msinvokeAll
The calls overlap, so the total is the slowest one.
var fs = pool.invokeAll(List.of(
menuTask, priceTask, etaTask));
String menu = fs.get(0).get();
// total about 350 msThe shift: Running independent calls together turns a sum of delays into a maximum.
Land it I use invokeAll when I need every answer, invokeAny when any good answer will do, and I make sure the pool is big enough for them to overlap.
- "What happens to the tasks that lose in invokeAny?"
-
They are cancelled with
cancel(true), which means the pool interrupts the worker threads that are still running them. A task that is sleeping or blocked on a queue or socket seesInterruptedExceptionand can stop. A task in a tight computation loop does not notice and runs on.So
invokeAnydoes not guarantee that the losers have stopped, only that they were asked to. If the losers hold a resource (an open connection, a lock), they must release it in afinallyblock when interrupted.This is a form of the cancellation problem that E3 Q195 covers. The practical rule is to write every task so that interruption means "clean up and return quickly".
It also matters for cost. If each of three replicas costs money or load,
invokeAnystill sends all three requests. Hedging trades extra work for lower latency. - "How do the results of invokeAll arrive when a task fails?"
-
invokeAllnever throws because of a task failure. It returns all the futures, each done. The failure of one is stored inside that future, and shows up asExecutionExceptionwhen you callget()on it.That means you must check each future. A loop over the results with
get()will throw at the first failed one and you may miss the other results.- All or nothing: call
get()on each in order and let the first exception propagate. - Partial results: check
f.state()(Java 19) and collect successes and failures separately. - With a deadline: use the timeout version and check
isCancelled()for the ones that ran out of time.
For partial results in complex flows,
CompletableFuturewithhandleper call (Q90) is cleaner. - All or nothing: call
- "When would I use an ExecutorCompletionService instead?"
-
When you want to process results as they complete, not in submission order and not all at once.
ExecutorCompletionServicewraps an executor and gives youtake(), which returns the next finished future from a queue.The picture: you submit ten searches to ten providers. With
invokeAllyou wait for the slowest. With a completion service you handle the first answer in 250 ms, then the next, and can show partial results early.It is the middle option between
invokeAll(all) andinvokeAny(one). The cost is a bit more code, since you count how many results to collect and cancel the rest yourself.In new code I usually reach for
CompletableFuture.anyOfor structured concurrency (Q99) where the policy is a setting, but the completion service remains a simple, dependency-free tool. - "Does invokeAll preserve the order of results?"
-
Yes. The returned list has the same order as the input collection, whatever order the tasks finished in.
fs.get(0)is always the future for the first task you passed.That is convenient for the checkout example: menu first, price second, ETA third, and the code reading
get(0)knows which is which. For a list of many similar tasks it keeps results aligned with inputs.The order guarantee is one reason to pick
invokeAllover a completion service when you need results in input order.The task execution order is not guaranteed. They start in roughly the input order, but run concurrently, so side effects such as logging will interleave. Do not rely on one task having finished before the next starts.
Q75. "Explain a ThreadPoolExecutor's core size, max size, queue and rejection, in the order a task meets them."
Reveal answer
The real test Whether you state the surprising order: the pool creates threads up to core first, then fills the queue, and only when the queue is full creates extra threads up to max. A large unbounded queue means max is never reached.
Strong answer A ThreadPoolExecutor has five settings that interact: corePoolSize, maximumPoolSize, the work queue, the keep-alive time and a rejection handler. A submitted task meets them in a fixed order.
- Fewer than core threads running: start a new thread for this task, even if other threads are idle.
- Core threads all exist: try to put the task in the queue. If it fits, a worker will take it when free.
- Queue is full: if fewer than max threads exist, start an extra thread for the task.
- Queue full and max threads running: the task is rejected. The handler decides:
AbortPolicythrowsRejectedExecutionException,CallerRunsPolicyruns it on the submitting thread,DiscardPolicydrops it,DiscardOldestPolicydrops the oldest queued task.
The part most people get wrong is step 3. Threads beyond core are created only when the queue is full. With an unbounded queue (LinkedBlockingQueue with no limit) the queue is never full, so the pool never grows past core and max is ignored. That is the trap in Q76.
Keep-alive: threads above core that are idle longer than the keep-alive time are removed, so the pool shrinks back to core after a burst. allowCoreThreadTimeOut(true) lets core threads expire too.
A sound production setup has a bounded queue (say 100 to 1,000 entries), a max that suits the downstream, named threads and a rejection policy chosen on purpose: CallerRunsPolicy to slow producers down, or abort-and-shed to protect latency. The primer calls this Bounded pool.
E3 Q182 walks the same path, Q183 shows the unbounded-queue surprise and Q185 compares the four policies.
Picture it A pool with core 2, max 4 and a queue of 2, flooded with eight tasks that all wait on a gate.
The setup: a pool built like this:
ThreadPoolExecutor(2, 4, 30 s, ArrayBlockingQueue(2), AbortPolicy)Eight tasks are submitted. Every task waits on a CountDownLatch, so no worker frees up while we submit. After each submit the program prints the thread count and queue size.
import java.util.concurrent.*;
public class Q75Tpe {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 4, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2),
new ThreadPoolExecutor.AbortPolicy());
CountDownLatch gate = new CountDownLatch(1);
for (int i = 1; i <= 8; i++) {
int id = i;
try {
pool.execute(() -> {
try { gate.await(); } catch (InterruptedException e) { }
System.out.println("task " + id + " ran on " + Thread.currentThread().getName());
});
System.out.println("task " + id + " accepted -> threads=" + pool.getPoolSize() + " queue=" + pool.getQueue().size());
} catch (RejectedExecutionException e) {
System.out.println("task " + id + " REJECTED -> threads=" + pool.getPoolSize() + " queue=" + pool.getQueue().size());
}
}
gate.countDown();
pool.shutdown();
pool.awaitTermination(2, TimeUnit.SECONDS);
}
}Make the invisible visible: Run it and read the accepted and rejected lines in order.
task 1 accepted -> threads=1 queue=0
task 2 accepted -> threads=2 queue=0
task 3 accepted -> threads=2 queue=1
task 4 accepted -> threads=2 queue=2
task 5 accepted -> threads=3 queue=2
task 6 accepted -> threads=4 queue=2
task 7 REJECTED -> threads=4 queue=2
task 8 REJECTED -> threads=4 queue=2
task 6 ran on pool-1-thread-4
task 1 ran on pool-1-thread-1
task 5 ran on pool-1-thread-3
task 3 ran on pool-1-thread-1
task 2 ran on pool-1-thread-2
task 4 ran on pool-1-thread-4What you see: Tasks 1 and 2 each started a core thread. Tasks 3 and 4 went into the queue (threads stayed at 2). Only when the queue was full did tasks 5 and 6 create threads 3 and 4. Tasks 7 and 8 were rejected, with 4 threads and a full queue of 2.
Why: That is the order: core, queue, max, reject. After the gate opened the six accepted tasks ran. The order they printed in is not the submit order, because the four threads race to print once the gate opens.
// illustrative - the decision path of execute(task)
submit(task)
|-- threads < core? ----------- yes --> start new core thread
|-- queue.offer(task) succeeds? yes --> wait in queue
|-- threads < max? ------------ yes --> start extra thread
'-- otherwise ------------------------> rejection handlerUnbounded queue
The queue never fills, so max is never used.
new ThreadPoolExecutor(
10, 200, 30, SECONDS,
new LinkedBlockingQueue<>());
// stays at 10 threads forever
// queue grows without limitBounded queue
The queue fills, extra threads start, then rejection.
new ThreadPoolExecutor(
10, 200, 30, SECONDS,
new ArrayBlockingQueue<>(100),
new CallerRunsPolicy());
// grows to 200 under loadThe shift: A bounded queue is what makes the maximum size and the rejection policy real.
Land it I explain the order as core threads first, then the queue, then extra threads up to max, then rejection, and I remind everyone that an unbounded queue disables max.
- "Why does the pool prefer to queue before adding threads beyond core?"
-
It is a design choice made in the original
ThreadPoolExecutor: threads are expensive and queues are cheap, so the pool tries to absorb a burst with the threads it already has. It adds more only when waiting is no longer acceptable, which it defines as "the queue is full".The effect is that your queue size is the burst you tolerate before the pool grows. A queue of 100 means "up to 100 tasks may wait before I add a thread". A queue of 0 (a
SynchronousQueue, as innewCachedThreadPool) means "add a thread immediately".If you want a pool that grows before queueing, there is no setting. You use a custom queue whose
offerreturns false while threads are below max (as some frameworks such as Tomcat do), or you use a cached pool with a semaphore.E3 Q183 explains this with a core=10, max=200 pool that never grows.
- "Which rejection policy should I pick?"
-
It depends on who can be slowed down and what may be lost.
Policy Pick it when Cost or catch AbortPolicy(default)You want a loud failure, or can shed load at the edge The caller must handle RejectedExecutionExceptionCallerRunsPolicyYou want back-pressure: producers slow down Runs on the caller, which may be an event loop or a request thread DiscardPolicyWork is optional (metrics, hints) Silent loss DiscardOldestPolicyFresh work matters more than old Silent loss of the longest-waiting task I default to
CallerRunsPolicyinside batch jobs andAbortPolicywith a 429 or 503 response at a service edge. E3 Q185 discusses when each one is a feature and when a trap. - "What does the keep-alive time do?"
-
It decides when idle extra threads die. After a burst created threads up to max, any thread beyond core that has been idle for the keep-alive time (30 seconds in the demo) is terminated. The pool returns to its core size.
Core threads normally live forever, even when idle.
allowCoreThreadTimeOut(true)makes them follow the same timeout, useful for pools that are used rarely, such as a nightly job.The setting affects cost and latency, not correctness. A short keep-alive saves memory but pays thread creation again at the next burst. A long one keeps threads warm.
For a steady service I use a keep-alive of 30 to 60 seconds. For spiky load, longer.
- "How do I watch a pool's state in production?"
-
The pool exposes what you need through getters, and a metrics library can publish them.
- Queue size (
getQueue().size()): a rising line means producers are faster than workers. - Active count and pool size: active equal to pool size means the pool is saturated.
- Completed task count and rejected count (count rejections in your handler): throughput and shedding.
- Largest pool size: shows whether the pool ever grew beyond core.
Micrometer's
ExecutorServiceMetricspublishes these for Prometheus. An alert on "queue size above 80 percent of capacity for 1 minute" catches the problem before rejections begin. - Queue size (
Q76 · Scenario. "Executors.newFixedThreadPool caused an OutOfMemoryError. Why?"
Reveal answer
Strong answer Because newFixedThreadPool(n) builds a pool with n threads and an unbounded queue. Inside it is this:
new ThreadPoolExecutor(n, n, 0, SECONDS, new LinkedBlockingQueue<>())and a LinkedBlockingQueue with no capacity accepts tasks until the heap runs out.
The failure happens when tasks arrive faster than the workers finish them. Say a downstream service slows from 50 ms to 5 seconds. The 50 workers now finish 10 tasks a second, requests keep arriving at 1,000 a second, and 990 tasks a second pile up in the queue. Each queued task is an object holding its captured data (request body, order, connection), so memory grows until OutOfMemoryError: Java heap space.
The cruel part is that nothing warns you. The pool never rejects, submit always succeeds, and latency grows quietly as the queue lengthens. The first sign is often GC activity climbing and then the crash, and the heap dump shows millions of FutureTask or Runnable objects inside a LinkedBlockingQueue (E3 Q186).
The fix is a bounded queue and a decision about overload. Build the ThreadPoolExecutor yourself with new ArrayBlockingQueue<>(1000) and a rejection policy: CallerRunsPolicy slows producers, AbortPolicy lets you return an error quickly. Add a metric on queue size and an alert before it fills.
A bounded queue is a statement of policy: "this is how much work I will hold; beyond that I push back". Without it, memory is the queue, and memory is the worst place to discover your limit.
The primer shows this as Bounded pool. E3 Q186 is the heap-dump version, and Q75 above explains why the pool never grows to its max.
Picture it A fixed pool of 2 threads whose tasks are stuck behind a slow downstream, with the heap capped at 64 MB.
The setup: newFixedThreadPool(2). Every task waits on a latch that never opens, standing in for a downstream that never answers. Each task also carries a 100 KB payload. The program keeps submitting until the JVM runs out of memory. It runs with -Xmx64m so it ends quickly, and a 4 MB reserve array is released so the program can still print.
import java.util.concurrent.*;
public class Q76FixedOom {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2); // unbounded LinkedBlockingQueue inside
CountDownLatch slowDownstream = new CountDownLatch(1); // the downstream never answers
byte[] reserve = new byte[4_000_000]; // lets us print after the crash
int submitted = 0;
try {
while (true) {
byte[] payload = new byte[100_000]; // each queued task carries 100 KB
pool.execute(() -> { try { slowDownstream.await(); } catch (InterruptedException e) { } payload[0] = 1; });
submitted++;
}
} catch (OutOfMemoryError e) {
reserve = null;
((ThreadPoolExecutor) pool).getQueue().clear(); // drop the backlog
System.out.println("OutOfMemoryError after submitting " + submitted + " tasks");
System.out.println("message: " + e.getMessage());
} finally {
slowDownstream.countDown();
pool.shutdownNow();
}
}
}Make the invisible visible: Run it with a small heap.
OutOfMemoryError after submitting 566 tasks
message: Java heap spaceWhat you see: The pool accepted 566 tasks without any complaint, then the heap was full. Only 2 tasks were running. The other 564 sat in the queue, holding their payloads.
Why: There was no limit anywhere, so the first signal was the crash itself. With a bounded queue of, say, 100 the 101st submit would have been rejected immediately and the caller could have slowed down or failed fast. The count 566 depends on the heap size and payload, so yours will differ.
newFixedThreadPool
Unbounded queue hidden inside. Overload becomes memory.
var pool = Executors
.newFixedThreadPool(50);
// queue: LinkedBlockingQueue
// capacity: Integer.MAX_VALUEBounded ThreadPoolExecutor
A limit and a rule for what happens beyond it.
var pool = new ThreadPoolExecutor(
50, 50, 0, SECONDS,
new ArrayBlockingQueue<>(1000),
new CallerRunsPolicy());The shift: The bounded version moves the overload decision from "the JVM crashes" to "my code says what to do".
Land it I never use newFixedThreadPool for work that can pile up, because its hidden unbounded queue turns slow downstream calls into an OutOfMemoryError.
- "How big should the bounded queue be?"
-
Big enough to absorb a normal burst, small enough that a task waiting in it is still worth running. A practical method is to start from latency. If workers handle a task in 50 ms and 50 workers give 1,000 tasks a second, a queue of 1,000 means the last task waits about one second. If your timeout is two seconds, a queue of 2,000 would already be full of tasks whose callers gave up.
So queue length times service time divided by workers is the added wait, and it must stay under your timeout. A queue that is longer than the timeout only stores work nobody wants.
Start small (100 to 1,000), watch the queue-size metric and the rejection count, and adjust. Rising rejections with idle workers mean the queue is too small for bursts. Rising queue wait with busy workers mean you need more capacity, not a bigger queue.
E3 Q184 has the full sizing worked out.
- "Does newCachedThreadPool fix it?"
-
It swaps the problem. A cached pool has no queue at all (a
SynchronousQueue) and a max ofInteger.MAX_VALUEthreads, so every task that finds no idle worker gets a new thread. Under overload you do not run out of heap first, you run out of threads and memory for stacks, and seeOutOfMemoryError: unable to create native thread.It is fine for a modest number of short-lived tasks, where the number of simultaneous tasks is naturally small. It is dangerous when the task count follows request volume.
The safe designs are the same for both: set a hard upper bound, decide what happens beyond it, and measure.
- CPU work: a fixed pool near the core count with a bounded queue.
- Blocking I/O: virtual threads plus a
Semaphoreon the downstream (Q80, Q95).
- "What does CallerRunsPolicy do under this overload?"
-
When the pool and queue are full, the policy runs the rejected task on the thread that called
submit. That thread is now busy doing the work itself, so it cannot submit more. The producer slows to the speed of the consumers, which is natural back-pressure.It works well when the producer is a batch loop or a message consumer that can wait. Messages simply back up in the broker instead of in your heap.
It is dangerous when the caller is a request thread that must answer quickly, because the request now does a slow task inline. And if the caller is an event-loop thread, it blocks the loop.
It can also run a task on a thread that holds a lock the task needs. So I use it for batch and consumer loops, and choose
AbortPolicywith a 503 for request threads. E3 Q185 has the longer discussion. - "How would I confirm this was the cause from a heap dump?"
-
Open the dump in a tool such as Eclipse MAT or VisualVM and look at the dominator tree. The biggest retained object will be a
LinkedBlockingQueue(or itsNodechain) owned by aThreadPoolExecutor.- Find the queue: the top entry in the dominator tree, with a retained size close to the whole heap.
- Count the nodes: the
countfield of the queue gives the backlog, here 566 in the demo and millions in a real incident. - Inspect one task: the lambda or
FutureTaskshows which code submitted it and what data it holds, which tells you the producer.
Then confirm with metrics: queue size rising for minutes before the crash. The fix goes in the pool definition, and an alert on queue size prevents a repeat.
Q77. "How do you shut down an executor correctly — and what changed in Java 19?"
Reveal answer
Strong answer An executor's worker threads are not daemon threads, so a pool you forget to stop keeps the JVM alive after main ends. A clean shutdown has two parts: stop accepting work, then wait for what is running.
shutdown() is the polite call. It rejects new tasks (a later submit throws RejectedExecutionException), but lets running and queued tasks finish. It returns at once, so it does not wait. awaitTermination(timeout, unit) waits for the finish and returns true if it completed in time.
shutdownNow() is the forceful call. It tries to stop running tasks by interrupting the workers, empties the queue and returns the list of tasks that never started. Tasks that ignore interruption keep running.
The standard recipe is three steps: call shutdown(), call awaitTermination with a sensible limit, and if that returns false call shutdownNow() and wait once more. This gives tasks a fair chance to finish and a hard stop if they do not.
Java 19 change: ExecutorService now extends AutoCloseable. Its close() method does the recipe for you: it calls shutdown() and waits, and if the waiting thread is interrupted it calls shutdownNow(). So a try-with-resources block shuts the pool down at its end. The compile proof is below: the same code fails on --release 18 and compiles on 19.
One limit: close() waits without a timeout. A task that never finishes keeps close() waiting. For services with a deadline I still write the timed recipe.
The primer shows Clean shutdown. E3 Q187 compares shutdown and shutdownNow in depth.
Picture it Each shutdown style with three 300 ms jobs on a single worker, then the Java 19 compile proof.
The setup: First shutdown() plus awaitTermination. Then shutdownNow() 100 ms after the first job started. Then try-with-resources. A final small file proves the language change with javac --release.
import java.util.List;
import java.util.concurrent.*;
public class Q77Shutdown {
static void job(int id, int ms) {
try { Thread.sleep(ms); System.out.println("job " + id + " finished"); }
catch (InterruptedException e) { System.out.println("job " + id + " INTERRUPTED"); }
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(1);
for (int i = 1; i <= 3; i++) { int id = i; pool.submit(() -> job(id, 300)); }
pool.shutdown();
try { pool.submit(() -> job(99, 1)); } catch (RejectedExecutionException e) { System.out.println("after shutdown(): new task rejected"); }
System.out.println("awaitTermination(2 s) -> " + pool.awaitTermination(2, TimeUnit.SECONDS));
System.out.println("--- shutdownNow");
ExecutorService pool2 = Executors.newFixedThreadPool(1);
for (int i = 1; i <= 3; i++) { int id = i; pool2.submit(() -> job(id, 300)); }
Thread.sleep(100);
List<Runnable> neverStarted = pool2.shutdownNow();
System.out.println("shutdownNow() returned " + neverStarted.size() + " tasks that never started");
pool2.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("--- try-with-resources (Java 19+)");
try (ExecutorService pool3 = Executors.newFixedThreadPool(2)) {
pool3.submit(() -> job(7, 200)); pool3.submit(() -> job(8, 200));
} // close() = shutdown + awaitTermination
System.out.println("pool3 closed, all jobs done");
}
}Make the invisible visible: Run it.
after shutdown(): new task rejected
job 1 finished
job 2 finished
job 3 finished
awaitTermination(2 s) -> true
--- shutdownNow
shutdownNow() returned 2 tasks that never started
job 1 INTERRUPTED
--- try-with-resources (Java 19+)
job 7 finished
job 8 finished
pool3 closed, all jobs doneWhat you see: After shutdown() a new task was rejected, but all three jobs finished. With shutdownNow() the running job was interrupted, two queued jobs never started and were handed back. The try-with-resources block waited for both jobs.
Make the invisible visible: Now the compile proof for the Java 19 change.
import java.util.concurrent.*;
public class Q77Twr {
public static void main(String[] args) {
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
pool.submit(() -> System.out.println("hello"));
}
}
}Q77Twr.java:5: error: incompatible types: try-with-resources not applicable to variable type
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
^
(ExecutorService cannot be converted to AutoCloseable)
1 error
--- javac --release 19: exit 0Why: Before Java 19 the compiler says ExecutorService cannot be converted to AutoCloseable. With --release 19 it compiles with no output and exit code 0.
Before Java 19
Three calls and a try/finally by hand.
pool.shutdown();
if (!pool.awaitTermination(30, SECONDS)) {
pool.shutdownNow();
}Java 19 and later
try-with-resources calls close(): shutdown and wait.
try (var pool =
Executors.newFixedThreadPool(4)) {
pool.submit(task1);
pool.submit(task2);
} // all tasks done hereThe shift: close() packs "stop accepting, wait for the rest" into the language's own resource syntax.
Land it I stop a pool with shutdown, then awaitTermination, then shutdownNow as the last resort, and since Java 19 I let try-with-resources do the first two.
- "What should awaitTermination's timeout be?"
-
Tie it to something real: the platform's grace period, or the longest task you accept. In Kubernetes a pod gets 30 seconds by default after SIGTERM, so a pool should finish well inside that, for example 20 seconds, leaving room for the rest of the shutdown.
The recipe is two stages. Wait up to the limit for polite finish. If it returns false, call
shutdownNow()to interrupt, then wait a short second time (5 seconds) so interrupted tasks can clean up. If that also returns false, log it with the pool name and give up, because the process will be killed anyway.A very long or zero timeout hides the problem. A task that never ends should be a log line you can find, not a pod that is killed with no explanation.
The same budget logic applies to shutdown hooks and to Spring's graceful shutdown (E4).
- "What do the interrupted tasks need to do?"
-
They must notice and stop.
shutdownNow()only sets the interrupt flag on each worker. A task that is sleeping or blocked on a queue getsInterruptedException. A task in a computation loop must checkThread.currentThread().isInterrupted()itself.On interruption a good task does four things: stop taking new work, release what it holds (connections, locks) in
finally, restore the interrupt flag if it caughtInterruptedExceptionand cannot rethrow it, and return quickly.The common bug is an empty
catch (InterruptedException e) {}inside a retry loop. The task swallows the signal and keeps running, and shutdown then hangs until the process is force-killed (E3 Q179).In the demo, job 1 printed INTERRUPTED because
sleepwoke with the exception. The two queued jobs never started, which is exactly the listshutdownNow()returned. - "Why not rely on a shutdown hook to stop the pool?"
-
A JVM shutdown hook runs when the JVM is asked to exit (SIGTERM,
System.exit), so it is a good place to call your shutdown recipe. But a hook is the last resort, not the design.It has no guarantee on a hard kill (SIGKILL, power loss), runs concurrently with other hooks in no fixed order, and a hung hook blocks exit. Frameworks such as Spring register their own ordered lifecycle so that web threads stop before pools and pools stop before connections.
My design is to give each component a
close()or@PreDestroymethod, stop things in reverse order of starting, and use the hook only to trigger that sequence. Tasks should also be safe to repeat, because a forced kill can interrupt the middle of one. - "Is it a problem to create a pool inside a method?"
-
It is if the method is called often. A pool created per call and closed at the end costs thread creation every time, which removes the benefit of pooling. The common bug is a pool created per request and never shut down: each one leaks threads until the process dies.
A pool is a long-lived resource: create once (a bean, a static final, or application start-up), share it, and close it on shutdown.
The exception is the batch-method pattern, where one method fans out a bounded job and finishes: a pool in a try-with-resources block is neat there because its lifetime matches the job (the Q71 demo does exactly this). With virtual threads, a short-lived executor per job is even cheap, because creating one involves no thread startup.
Q78 · Scenario. "A scheduled job silently stopped running last week. Why?"
Reveal answer
Strong answer Almost certainly because one run threw an exception. For scheduleAtFixedRate and scheduleWithFixedDelay the rule in the documentation is blunt: if any execution throws, subsequent executions are suppressed. The schedule is cancelled, the pool thread lives on, and nothing is logged.
The exception is not lost. It is stored in the ScheduledFuture that the schedule call returned. If nobody ever calls get() on it, nobody ever sees it. That matches the story exactly: the job ran fine for weeks, one flaky downstream call threw once, and from then on there was silence.
The fix is to catch everything inside the task body and log it. A run that fails should log, count a metric, and let the next run happen. Catch Exception, and consider Throwable if you want to survive even errors such as OutOfMemoryError from a single bad batch (many teams log and continue on Exception only).
Add a heartbeat as well: a metric such as "last successful run time", with an alert when it is older than three periods. That catches the silent stop even from a cause you did not predict, such as a hung run that never returns (one hung run also blocks later runs, because one schedule never overlaps itself).
Other causes to rule out: the pool was shut down, a deploy replaced the instance without scheduling the job, or the job runs in a newScheduledThreadPool(1) shared with a task that blocks. A thread dump of the scheduler thread shows which.
The primer covers this in Executors. E3 Q188 is the same incident as an interview scenario.
Picture it A periodic task that throws on its third tick, with and without a try/catch.
The setup: A one-thread scheduler runs a task every 200 ms. The unprotected version throws on tick 3. After 1.2 seconds the program checks the future and reads its stored exception. The protected version catches the same failure and carries on.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q78Scheduled {
public static void main(String[] args) throws Exception {
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
AtomicInteger n = new AtomicInteger();
ScheduledFuture<?> bad = ses.scheduleAtFixedRate(() -> {
int tick = n.incrementAndGet();
System.out.println("sync tick " + tick);
if (tick == 3) throw new IllegalStateException("flaky downstream");
}, 0, 200, TimeUnit.MILLISECONDS);
Thread.sleep(1200);
System.out.println("after 1.2 s: isDone=" + bad.isDone() + " (the schedule is dead)");
try { bad.get(); } catch (ExecutionException e) { System.out.println("the hidden exception: " + e.getCause()); }
AtomicInteger m = new AtomicInteger();
ScheduledFuture<?> good = ses.scheduleAtFixedRate(() -> {
try {
int tick = m.incrementAndGet();
System.out.println("safe tick " + tick);
if (tick == 3) throw new IllegalStateException("flaky downstream");
} catch (Exception e) {
System.out.println(" logged and carried on: " + e.getMessage());
}
}, 0, 200, TimeUnit.MILLISECONDS);
Thread.sleep(1100);
System.out.println("isDone=" + good.isDone());
ses.shutdownNow();
}
}Make the invisible visible: Run it.
sync tick 1
sync tick 2
sync tick 3
after 1.2 s: isDone=true (the schedule is dead)
the hidden exception: java.lang.IllegalStateException: flaky downstream
safe tick 1
safe tick 2
safe tick 3
logged and carried on: flaky downstream
safe tick 4
safe tick 5
safe tick 6
isDone=falseWhat you see: The unprotected job printed ticks 1, 2, 3 and then nothing for a full second. Its future was done, and the hidden exception was only visible by calling get(). The protected job logged the failure on tick 3 and kept going to tick 6, with isDone=false.
Why: The scheduler treats a thrown exception as "this task is broken, stop it". Catching it yourself tells the scheduler the run was fine, so the schedule continues.
Exception escapes
One failure cancels every later run, silently.
ses.scheduleAtFixedRate(() -> {
syncMenus(); // may throw once
}, 0, 1, TimeUnit.MINUTES);
// after one throw: no more runsCatch inside the task
A failed run is logged and the next one still happens.
ses.scheduleAtFixedRate(() -> {
try { syncMenus(); }
catch (Exception e) { log.error("sync", e); }
}, 0, 1, TimeUnit.MINUTES);The shift: A periodic task must never let an exception out, or the scheduler concludes it is finished.
Land it I wrap every periodic task body in try/catch with logging and add a last-success metric, because one uncaught exception cancels the schedule without a sound.
- "What is the difference between fixed rate and fixed delay?"
-
Both repeat a task. Fixed rate starts runs at 0, period, 2 times period and so on, measured from the first start. If a run takes longer than the period, the next one starts as soon as the last ends (runs never overlap, but they bunch up to catch up).
Fixed delay waits the delay after each run finishes before starting the next. A 200 ms delay and a 300 ms run give a start every 500 ms.
My choice: fixed rate when the schedule matters ("every minute, on the minute") and the task is short. Fixed delay when the task length varies and I want a guaranteed pause between runs, which protects a downstream from overlap and back-to-back load.
In both, a slow run delays the next ones, because a single schedule runs on one thread at a time. A 10-minute run in a 1-minute schedule means skipped minutes.
- "How can I tell from outside that the job stopped?"
-
You cannot from the JVM's normal output, which is why the metric matters. Four signals work.
- Last-success timestamp exported as a gauge; alert when "now minus last success" exceeds three periods.
- Run counter: a counter that should rise every minute; alert on a flat line.
- Thread dump: the scheduler thread idle in
DelayedWorkQueue.takewith an empty queue means nothing is scheduled. - The future: keep the
ScheduledFutureand have a watcher callisDone(); a periodic task that is done has died.
Absence of a log line is the hardest alert to write, so I always emit a positive "job ran" signal.
- "Do Spring's @Scheduled methods have the same problem?"
-
No, and the reason is instructive. Spring's scheduler wraps each run in a
DelegatingErrorHandlingRunnablethat catches exceptions, logs them, and lets the schedule continue. A@Scheduledmethod that throws is logged as an error and runs again next time.That is the safe behaviour I am recommending by hand, built into the framework (E4). If you use the raw JDK
ScheduledExecutorServiceyou get none of it.Spring has its own pitfalls. The default scheduler uses a single thread, so one slow
@Scheduledjob delays every other. Settingspring.task.scheduling.pool.sizefixes that. And in a cluster, every instance runs the job, so you need a lock (ShedLock or a database row) if it must run once. - "When should I not use a ScheduledExecutorService?"
-
When the job must survive a restart, run once across a cluster, or follow a calendar. The JDK scheduler is in memory: a redeploy forgets everything, two instances run everything twice, and it has no "every weekday at 9" rule.
For those needs I use a job scheduler with persistence (Quartz, a database-backed queue, a Kubernetes CronJob) or a message broker with delayed delivery.
The JDK scheduler is right for in-process housekeeping: refresh a cache every minute, flush a buffer every second, send a heartbeat. These are cheap, safe to repeat, and correct for each instance to do on its own.
Q79. "Why should pool threads have names, and how do you set them?"
Reveal answer
Strong answer Because every tool that shows threads shows their names, and the default names tell you nothing. A thread dump, a profiler, a log line and a CPU graph all identify a thread by name. The default pool names are pool-1-thread-1, pool-2-thread-1, and so on. With six pools in a service, "pool-3-thread-7 is stuck" means nothing.
A good name says which pool and which worker: notify-0, payments-3, checkout-io-1. Then a dump that shows ten threads BLOCKED named payments-* points at once to the payments pool, and a log line tagged with the thread name shows which component did the work.
Names also help with filtering. Monitoring can group CPU by thread-name prefix. Logs can be searched by pool. And tests can assert on Thread.currentThread().getName().
There are three ways to set a name. The simplest in Java 21 is Thread.ofPlatform().name("notify-", 0).factory(), which gives a ThreadFactory that numbers threads from 0. A custom ThreadFactory lambda also lets you set daemon status and an uncaught-exception handler. Guava's ThreadFactoryBuilder does the same if you already use Guava.
Pass the factory to the executor: Executors.newFixedThreadPool(8, factory). For virtual threads use Thread.ofVirtual().name("order-", 0).factory(), since virtual threads have empty names by default.
A related habit: name threads at creation, not later with setName inside the task, because a dump taken before the task starts would still show the old name. The primer lists this as Name your threads. E3 Q141 shows how to read a dump once threads have good names.
Picture it The default name, two ways to set a name, and what a named thread looks like to a tool.
The setup: A pool with the default factory, one with Thread.ofPlatform() (Java 21), and one with a custom ThreadFactory. Each prints its worker's name. A last pool parks a thread and the program lists threads whose name begins with notify-, as you would grep a dump.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q79Names {
public static void main(String[] args) throws Exception {
try (ExecutorService def = Executors.newFixedThreadPool(2)) {
def.submit(() -> System.out.println("default factory: " + Thread.currentThread().getName())).get();
}
ThreadFactory named = Thread.ofPlatform().name("notify-", 0).factory(); // Java 21
try (ExecutorService a = Executors.newFixedThreadPool(2, named)) {
for (int i = 0; i < 2; i++) a.submit(() -> System.out.println("Thread.ofPlatform: " + Thread.currentThread().getName()));
}
AtomicInteger seq = new AtomicInteger();
ThreadFactory custom = r -> { Thread t = new Thread(r, "payments-" + seq.incrementAndGet()); t.setDaemon(true); return t; };
try (ExecutorService b = Executors.newFixedThreadPool(2, custom)) {
b.submit(() -> System.out.println("custom factory: " + Thread.currentThread().getName())).get();
}
// What a thread dump header looks like with a name
ExecutorService c = Executors.newFixedThreadPool(1, named);
c.submit(() -> { try { Thread.sleep(60_000); } catch (InterruptedException e) { } });
Thread.sleep(200);
for (Thread t : Thread.getAllStackTraces().keySet())
if (t.getName().startsWith("notify-")) System.out.println("in a dump you would grep for: \"" + t.getName() + "\" state=" + t.getState());
c.shutdownNow();
}
}Make the invisible visible: Run it.
default factory: pool-1-thread-1
Thread.ofPlatform: notify-0
Thread.ofPlatform: notify-1
custom factory: payments-1
in a dump you would grep for: "notify-2" state=TIMED_WAITINGWhat you see: The default factory gave pool-1-thread-1. The two named pools gave notify-0, notify-1 and payments-1. The last line shows a thread you could find by name, notify-2, parked in TIMED_WAITING. The number is 2 because the shared factory had already created two threads.
Why: In a real dump, a header such as "notify-2" #31 [12345] prio=5 would be searchable. The generic default would not tell you which of your pools it belonged to.
Default names
Numbers only. Which pool is pool-3?
var pool = Executors
.newFixedThreadPool(8);
// "pool-1-thread-1"
// "pool-2-thread-1" ... who owns it?Named factory
The name says whose thread it is.
var f = Thread.ofPlatform()
.name("notify-", 0).factory();
var pool = Executors
.newFixedThreadPool(8, f); // notify-0 ..The shift: A one-line factory turns anonymous workers into threads you can find in a dump at 2 a.m.
Land it I give every pool a named ThreadFactory, because a dump full of pool-N-thread-M names is a puzzle at the worst moment.
- "What else should a ThreadFactory set?"
-
Four properties are worth setting on purpose.
- Name: prefix plus counter, as above.
- Daemon flag: daemon threads do not keep the JVM alive. Background helpers can be daemon, but threads doing work that must finish should be non-daemon so shutdown waits.
- Uncaught-exception handler: log the exception with the thread name. It catches failures from
executetasks (Q72). - Priority and context class loader: usually leave alone, but a pool created inside a web application may need the right class loader.
I keep one small factory helper in the codebase so every pool is built the same way.
- "How do names help in a thread dump?"
-
A dump lists every thread with its name, state and stack. With good names you can summarise in seconds: count threads by prefix and state.
For example, if the dump shows 200 threads named
http-nio-8080-exec-*all BLOCKED, the web pool is stuck. If 8 threads namedpayments-*are RUNNABLE inside a socket read, the payments call is slow. If thenotify-*workers are all WAITING inLinkedBlockingQueue.take, that pool is idle and healthy.A short shell line does the counting: grep the thread header lines, cut off the number, and sort and count. It works only because the names carry a stable prefix.
Without names the same dump shows
pool-7-thread-3and you must read stack frames for each to guess the owner. E3 Q141 covers reading states. - "Do virtual threads have names?"
-
By default no: a virtual thread's name is the empty string, and its
toStringshows the id and carrier, likeVirtualThread[#26]/runnable@ForkJoinPool-1-worker-1. Q94's demo shows this.You can name them:
Thread.ofVirtual().name("order-", 0).start(...)or a factory from the same builder, which also works withExecutors.newThreadPerTaskExecutor(factory).Names matter more with virtual threads, because there can be 100,000 of them. A regular
jstackdoes not list virtual threads (it shows carriers). To see them usejcmd <pid> Thread.dump_to_file -format=json file, which includes virtual threads and their names.I name them by task kind and id:
order-1234makes a dump readable. - "Can a name hurt?"
-
Rarely, in two ways. A name built from request data (a customer email) can leak personal data into dumps and logs, so use ids, not personal details. And changing names often costs a little:
setNameon a running thread is cheap, but an expensive string built per task adds up at high rates.A subtler problem: threads reused across requests keep whatever name the last task set. Frameworks that rename threads to include a request id must restore the name in
finally, otherwise a later log line shows a stale request id.My rule: a stable pool prefix in the factory, and per-request context in a logging MDC (mapped diagnostic context), not in the thread name.
Q80. "CountDownLatch versus CyclicBarrier versus Semaphore — one real use each."
Reveal answer
Strong answer All three coordinate threads, and each answers a different question. A CountDownLatch asks "has everything I am waiting for happened yet?". A CyclicBarrier asks "have all of us arrived?". A Semaphore asks "is there room for one more?".
CountDownLatch is a one-shot gate. It starts at a count N. Worker threads call countDown() when they finish a step. Any thread that called await() is released when the count reaches 0. It cannot be reset. Real use: the kitchen starts cooking only after the grill, fryer and salad stations have reported ready, or a test waits for 20 async callbacks before asserting.
CyclicBarrier makes N threads wait for each other, then all proceed together, and it resets for the next round. An optional action runs when the last one arrives. Real use: three riders finish a delivery round, wait at the hub until all are back, then start the next round together. Used in parallel simulations and phased computations.
Semaphore holds a number of permits. acquire() takes one, waiting if none are left. release() gives one back. It limits how many threads are inside a section, not who. Real use: at most 20 concurrent calls to a fragile payment gateway.
The key differences: a latch counts events and any thread can count down, a barrier counts waiting threads and the participants are the waiters, and a semaphore counts available resources and has no fixed participants at all.
Choosing: waiting for events once, use a latch. Repeating group rendezvous, use a barrier (or the more flexible Phaser). Limiting concurrency, use a semaphore. Always release a semaphore in finally.
E3 Q206 covers latch against barrier, Q207 the semaphore limit, and Q208 the Phaser.
Picture it All three in one run, using QuickBite stories.
The setup: Three station threads count down a latch. Three rider threads meet at a barrier for two rounds. Then 200 virtual-thread tasks share a semaphore with 20 permits, and an atomic counter records the highest number of tasks inside at once.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q80Coordination {
public static void main(String[] args) throws Exception {
// CountDownLatch: wait ONCE for 3 kitchen stations
CountDownLatch stations = new CountDownLatch(3);
for (String s : new String[]{"grill", "fryer", "salad"}) {
new Thread(() -> { sleep(100 + (int) (Math.random() * 200)); System.out.println(s + " ready"); stations.countDown(); }).start();
}
stations.await();
System.out.println("latch opened: kitchen can start (count=" + stations.getCount() + ")");
// CyclicBarrier: 3 riders regroup EVERY round
CyclicBarrier regroup = new CyclicBarrier(3, () -> System.out.println(" --- all riders at the hub, next round ---"));
Thread[] riders = new Thread[3];
for (int r = 0; r < 3; r++) {
int id = r;
riders[r] = new Thread(() -> {
try {
for (int round = 1; round <= 2; round++) { sleep(50 + id * 60); System.out.println("rider " + id + " finished round " + round); regroup.await(); }
} catch (Exception e) { }
});
riders[r].start();
}
for (Thread t : riders) t.join();
// Semaphore: at most 20 concurrent calls to the payment gateway
Semaphore gateway = new Semaphore(20);
AtomicInteger inFlight = new AtomicInteger(), max = new AtomicInteger();
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 200; i++) pool.submit(() -> {
gateway.acquireUninterruptibly();
try {
int now = inFlight.incrementAndGet();
max.accumulateAndGet(now, Math::max);
sleep(20);
inFlight.decrementAndGet();
} finally { gateway.release(); }
});
}
System.out.println("semaphore(20): 200 calls, max in flight = " + max.get());
}
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
}Make the invisible visible: Run it.
fryer ready
salad ready
grill ready
latch opened: kitchen can start (count=0)
rider 0 finished round 1
rider 1 finished round 1
rider 2 finished round 1
--- all riders at the hub, next round ---
rider 0 finished round 2
rider 1 finished round 2
rider 2 finished round 2
--- all riders at the hub, next round ---
semaphore(20): 200 calls, max in flight = 20What you see: The stations reported in a random order, and the latch opened only after all three. The riders' round lines were always followed by the hub message, once per round, so the barrier reset itself. With 200 calls and 20 permits the highest number in flight was exactly 20.
Why: The latch fired once and stayed open. The barrier fired twice. The semaphore never fired at all: it only capped how many could be inside, and the 20 matches the permit count.
CountDownLatch — wait for events
One-shot: opens when the count reaches zero.
var ready = new CountDownLatch(3);
// each station: ready.countDown();
ready.await(); // kitchen waits
// opened for good; cannot resetSemaphore — limit concurrency
Permits go out and come back, again and again.
var gate = new Semaphore(20);
gate.acquire();
try { callGateway(); }
finally { gate.release(); }The shift: A latch counts events toward a goal, while a semaphore counts room that comes and goes.
Land it I use a latch to wait once for N things, a barrier to make a group meet every round, and a semaphore to cap how many can be inside at once.
- "Why does CyclicBarrier break if one thread fails?"
-
Because the group depends on every member. If one thread is interrupted, times out or throws while waiting, the barrier becomes broken: every other waiting thread gets a
BrokenBarrierExceptioninstead of hanging forever for a member that will never arrive.That is a safety feature. A latch has no such problem, because any thread can count down, and a missing count simply leaves waiters waiting, so use
await(timeout)on it.For the barrier I always use
await(timeout, unit)too. The timeout makes a missing rider a clearTimeoutException, not a frozen round.If the number of participants can change (riders join or leave), a barrier is the wrong tool. A
Phaserallows dynamic registration (E3 Q208). - "How is a Semaphore different from a thread pool limit?"
-
A pool size limits how many threads exist. A semaphore limits how many threads are inside one section, whatever the number of threads. That difference decides the choice.
With platform threads and blocking calls, shrinking the pool is the limit. With virtual threads you have no pool to shrink, because each task gets its own thread, so a
Semaphoreis how you protect a fragile downstream (Q95 and the primer's Semaphore limit). The demo above did exactly that: 200 virtual threads, 20 permits.A semaphore can also guard a section across several pools. Two services calling the same payment gateway can share one semaphore.
The costs: every user must acquire and release correctly, and a missed
releaseinfinallyleaks a permit until the gate closes for good. UsetryAcquire(timeout)to fail fast instead of queueing forever. - "Can a latch be reused?"
-
No. Once its count reaches zero it stays open, and
countDown()on an open latch does nothing. To wait for another round you create a new latch. That is the exact difference from the barrier, which resets.The one-shot design makes it simple to reason about: a latch is a flag that flips once, with a counter that decides when.
Two common uses besides "start gate" and "done gate". First, a start gate in tests: N threads await one latch with count 1, and the test releases it, so all start at the same moment and expose races. Second, a completion signal: await the latch in main until workers finish, as an alternative to joining each thread.
The demo's kitchen used the second form.
- "What happens if a thread forgets countDown() or release()?"
-
Both cases hang or starve, silently. If a worker throws before
countDown(), the latch never opens and waiters wait forever. The fix is to callcountDown()infinally, so a failed worker still counts.For a semaphore, a missing
release()leaks a permit. After 20 leaks, a 20-permit gate is closed forever, and every later caller blocks. The service looks healthy and the dump shows threads WAITING inSemaphore.acquire.- Always
finally:acquire(); try { ... } finally { release(); }. - Use timeouts:
await(timeout)andtryAcquire(timeout)turn a silent hang into a visible failure. - Monitor permits: export
availablePermits()as a gauge; a value that drifts to zero at idle means a leak.
- Always
These questions cover the tools between synchronized and a full framework: explicit locks, concurrent maps and queues. The common thread is that a safe part is not a safe whole.
Q81. "What does ReentrantLock give you that synchronized does not?"
Reveal answer
Strong answer ReentrantLock does the same basic job (mutual exclusion, visibility, reentrancy) but exposes the lock as an object, and that gives you five things synchronized cannot do.
- Try without waiting:
tryLock()returns at once with true or false, andtryLock(time, unit)waits only that long. A thread can give up and do something else instead of hanging. - Interruptible waiting:
lockInterruptibly()letsinterrupt()cancel a thread that is waiting for the lock. A thread waiting for asynchronizedmonitor stays BLOCKED and cannot be interrupted out. - Fairness:
new ReentrantLock(true)hands the lock to the longest-waiting thread. It prevents starvation but costs throughput (E3 Q200). - Multiple conditions:
lock.newCondition()gives several wait sets for one lock (for example "not full" and "not empty" on a buffer), where a monitor has one. - Inspection:
isLocked(),getQueueLength()andisHeldByCurrentThread()help diagnostics.
The price is discipline. You must unlock manually, and always in finally: lock.lock(); try { ... } finally { lock.unlock(); }. With synchronized the JVM releases the monitor on any exit. Forget the finally and an exception leaves the lock held forever.
It is also a library object, so tools see it differently, and virtual threads handle it well, since ReentrantLock never pinned a carrier. Since Java 24 synchronized no longer pins either (Q96).
My rule: use synchronized by default for its simplicity, and switch to ReentrantLock only when I need a timeout, interruption, a second condition or fairness. The primer shows them side by side in Synchronization. E3 Q196 asks when to switch, and Q197 covers Condition.
Picture it Timeout and interruption, which only the explicit lock offers.
The setup: A holder thread takes a ReentrantLock for 2.5 seconds. Main tries tryLock(), then tryLock(1, SECONDS). A waiter uses lockInterruptibly() and is interrupted. Then the same interruption is tried on a thread waiting for a synchronized monitor.
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class Q81Locks {
static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
Thread holder = new Thread(() -> {
lock.lock();
try { Thread.sleep(2500); } catch (InterruptedException e) { } finally { lock.unlock(); }
}, "holder");
holder.start();
Thread.sleep(100);
long t0 = System.nanoTime();
boolean got = lock.tryLock();
System.out.println("tryLock() -> " + got + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms");
t0 = System.nanoTime();
got = lock.tryLock(1, TimeUnit.SECONDS);
System.out.println("tryLock(1 s) -> " + got + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms (gave up, did not hang)");
// lockInterruptibly: a waiter we can cancel
Thread waiter = new Thread(() -> {
try { lock.lockInterruptibly(); } catch (InterruptedException e) { System.out.println("lockInterruptibly -> interrupted while waiting"); }
}, "waiter");
waiter.start(); Thread.sleep(200);
System.out.println("waiter state before interrupt: " + waiter.getState() + ", queue length " + lock.getQueueLength());
waiter.interrupt(); waiter.join();
// A synchronized waiter cannot be interrupted out of BLOCKED
Object mon = new Object();
Thread owner = new Thread(() -> { synchronized (mon) { try { Thread.sleep(1500); } catch (InterruptedException e) { } } });
owner.start(); Thread.sleep(100);
Thread blocked = new Thread(() -> { synchronized (mon) { System.out.println("synchronized waiter finally got in"); } });
blocked.start(); Thread.sleep(100);
blocked.interrupt(); Thread.sleep(200);
System.out.println("interrupted synchronized waiter is still " + blocked.getState());
owner.join(); blocked.join();
holder.interrupt();
}
}Make the invisible visible: Run it.
tryLock() -> false after 0 ms
tryLock(1 s) -> false after 1000 ms (gave up, did not hang)
waiter state before interrupt: WAITING, queue length 1
lockInterruptibly -> interrupted while waiting
interrupted synchronized waiter is still BLOCKED
synchronized waiter finally got inWhat you see: tryLock() failed instantly. tryLock(1 s) gave up after exactly 1,000 ms. The interruptible waiter, in state WAITING, was cancelled by interrupt(). The thread waiting for a monitor stayed BLOCKED after the interrupt, and finally got in when the owner left.
Why: A monitor wait has no way out except acquiring the monitor. A lock object's wait is a normal blocking call that responds to interruption and timeouts.
synchronized
Simple, released automatically, no timeout, not interruptible.
synchronized (lock) {
counter++;
}
// waits forever if the owner hangsReentrantLock
Explicit control: timeout, interruption, conditions.
if (lock.tryLock(1, SECONDS)) {
try { counter++; }
finally { lock.unlock(); }
} else { /* give up, retry later */ }The shift: synchronized gives you safety with no choices, and ReentrantLock gives you the choices at the price of a finally.
Land it I stay with synchronized until I need tryLock, interruptible waiting, several conditions or fairness, and then I use ReentrantLock with unlock in finally.
- "Why must unlock be in finally?"
-
Because an exception between
lock()andunlock()would skip the unlock, and the lock would stay held by that thread for the life of the JVM. Every other thread that needs it waits forever.With
synchronizedthe JVM does this for you, since the monitor is released when the block exits normally or by exception. The explicit lock hands you the responsibility.The standard shape never changes:
lock.lock();on its own line, before thetry, then thetryblock, thenfinally { lock.unlock(); }. Thelock()is outside the try so that if it fails (it rarely does) you do not unlock a lock you never took.With
tryLockthe unlock goes inside the success branch only, as in the duo above. A static-analysis rule or a code-review checklist item for "every lock has a finally" prevents the whole class of bugs. - "What is a Condition, and why is it better than wait and notify?"
-
A
Conditionis a wait set attached to aLock.await()releases the lock and waits.signal()wakes one waiter. It does the job ofwait/notify, with two upgrades.First, you can have several conditions on one lock. A bounded buffer uses
notFullfor producers andnotEmptyfor consumers. Asignal()then wakes the right kind of thread. With one monitor andnotify(), a producer may wake another producer, and a consumer never hears about the new item (E3 Q162).Second, the wait can have a timeout and a deadline, and an interruptible and uninterruptible form.
The rules from
waitstill hold: you must hold the lock when you callawaitorsignal, and you must callawaitin awhileloop that rechecks the condition, because of spurious wake-ups. In practice, I use aBlockingQueue(Q85) before writing one by hand. - "When is fairness worth its cost?"
-
When starvation is worse than lower throughput. A fair lock hands the lock to the thread that has waited longest, so no thread waits forever. A non-fair lock lets a newly arriving thread "barge in" ahead of waiters, which is faster because it avoids a thread wake-up, but one unlucky thread may wait very long.
The cost is real: fair locks are often several times slower under contention, because every hand-over needs the next waiter to be woken.
I choose fair when the lock protects a resource where waiting indefinitely would break a promise: a job queue where old jobs must run in order, or a scarce resource where one client must not be starved by others.
I choose non-fair (the default) for nearly everything else, and I measure first. Note that even fair locks cannot guarantee thread scheduling fairness, only the order of lock acquisition. E3 Q200 has the numbers.
- "Does ReentrantLock work well with virtual threads?"
-
Yes, and it always did. When a virtual thread blocks on a
ReentrantLockit parks, which unmounts the virtual thread from its carrier so the carrier can run other work.Before Java 24, a virtual thread blocked inside a
synchronizedblock was pinned: it held its carrier thread during the wait. That is why guidance for Java 21 said "prefer ReentrantLock in code that blocks inside the lock". JEP 491 in Java 24 removed that limit for monitors (Q96).So on Java 21 I replace
synchronizedwithReentrantLockaround blocking calls, and on 24 or newer I stop worrying, with one remaining exception: native frames and class initializers can still pin.
Q82. "ReadWriteLock and StampedLock — when is each worth it?"
Reveal answer
Strong answer Both are for data that is read far more often than it is written. A plain lock lets one thread in at a time, so readers queue behind each other even though reading together is harmless. These locks let many readers in at once and make a writer wait for exclusive access.
ReentrantReadWriteLock has a read lock and a write lock. Any number of threads may hold the read lock together, and the write lock is exclusive. Use it when reads are slow enough (a few microseconds or more), reads outnumber writes by something like 10 to 1, and you want simple, familiar semantics. The demo below shows 8 readers going 10 times faster than an exclusive lock.
StampedLock adds an optimistic read: tryOptimisticRead() returns a stamp without locking anything. You read the data, then call validate(stamp). If no writer got in meanwhile, you are done with no lock taken. If a writer did, validation fails and you fall back to a real read lock and read again. It is the fastest option for very read-heavy, short reads.
The sharp edges of StampedLock: it is not reentrant (taking the same lock twice deadlocks), it has no Condition, you must pass the right stamp to the right unlock method, and optimistic reads may see half-updated data until validated, so copy the fields to locals and validate before using them.
Neither helps when writes are common, when reads are very short (the lock bookkeeping costs more than the work), or when a single volatile reference to an immutable snapshot would do. Replacing the whole snapshot with one volatile write is often simpler and faster than either lock.
E3 Q198 describes a read-heavy cache that outgrew one lock, and Q199 covers the optimistic-read edges.
Picture it Eight readers, 40 reads each, with a "slow" read body, under three locking styles.
The setup: The read body is a short loop of arithmetic. The same load runs under an exclusive synchronized, a read lock and an optimistic StampedLock read. Each is run twice, and the second round (after warm-up) is reported. A writer is simulated at the end.
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class Q82RwLock {
static final Object plain = new Object();
static final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
static final StampedLock sl = new StampedLock();
static volatile int menuVersion = 7;
static void slowRead() { long x = 0; for (int i = 0; i < 2_000_000; i++) x += i; if (x == 42) System.out.println(); }
static long timeIt(Runnable reader) throws Exception {
Thread[] ts = new Thread[8];
long t0 = System.nanoTime();
for (int i = 0; i < 8; i++) { ts[i] = new Thread(() -> { for (int k = 0; k < 40; k++) reader.run(); }); ts[i].start(); }
for (Thread t : ts) t.join();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
for (int round = 0; round < 2; round++) { // second round is the warmed-up one
long a = timeIt(() -> { synchronized (plain) { slowRead(); } });
long b = timeIt(() -> { rw.readLock().lock(); try { slowRead(); } finally { rw.readLock().unlock(); } });
long c = timeIt(() -> {
long st = sl.tryOptimisticRead(); int v = menuVersion; slowRead();
if (!sl.validate(st)) { st = sl.readLock(); try { v = menuVersion; } finally { sl.unlockRead(st); } }
});
if (round == 1) {
System.out.println("8 readers, 40 reads each, 'slow' read body:");
System.out.println(" synchronized (exclusive): " + a + " ms");
System.out.println(" ReadWriteLock read lock: " + b + " ms");
System.out.println(" StampedLock optimistic: " + c + " ms");
}
}
// a writer invalidates an optimistic stamp
long st = sl.tryOptimisticRead();
long ws = sl.writeLock(); menuVersion = 8; sl.unlockWrite(ws);
System.out.println("validate() after a write -> " + sl.validate(st) + " (so the reader must retry with a real read lock)");
}
}Make the invisible visible: Run it.
8 readers, 40 reads each, 'slow' read body:
synchronized (exclusive): 354 ms
ReadWriteLock read lock: 34 ms
StampedLock optimistic: 22 ms
validate() after a write -> false (so the reader must retry with a real read lock)What you see: The exclusive lock took 354 ms because readers took turns. The read lock took 34 ms and the optimistic read 22 ms, because readers overlapped. After a write, the old stamp failed to validate.
Why: The exclusive lock serialised 320 slow reads. Shared and optimistic reads let up to 8 run at the same time on this 12-core machine. These are my timings on one run, so treat the ratio as the lesson, not the exact numbers.
Exclusive lock
Readers wait for each other.
synchronized (menu) {
return menu.price(item);
}
// 8 readers = 8 turnsRead lock
Readers share the lock. A writer waits for them to leave.
rw.readLock().lock();
try { return menu.price(item); }
finally { rw.readLock().unlock(); }The shift: Splitting readers from writers lets harmless concurrent reads run side by side.
Land it I reach for a read-write lock only when reads are frequent and slow enough to matter, and for StampedLock only after measuring and accepting its sharp edges.
- "Can a read lock be upgraded to a write lock?"
-
Not with
ReentrantReadWriteLock. If a thread holding the read lock asks for the write lock, it waits for all readers to leave, including itself, and so deadlocks. The lock allows the other direction: a writer may downgrade by taking the read lock before releasing the write lock.The safe pattern for "read, then maybe write" is: release the read lock, take the write lock, recheck the condition (another thread may have changed it), and act.
StampedLockofferstryConvertToWriteLock(stamp), which succeeds only if no other reader is present, and otherwise returns 0, so you fall back to the release-and-retake path.Because of this I design update paths as "take write lock, check, change" when updates are rare, and keep reads on the cheap path.
- "Why are readers sometimes slower under a read-write lock than under synchronized?"
-
Because the read-lock bookkeeping is not free. Each read acquisition updates a shared counter with an atomic operation, which makes the cache line bounce between cores. When the read work is only a few nanoseconds (a field or a small map lookup), that overhead dominates, and plain
synchronizedor a volatile reference to an immutable object wins.The break-even depends on the machine, but a useful rule is: if the protected read takes less than about a microsecond, do not use a read-write lock.
In the demo each read does about 2 million additions, large enough to dominate. A cache lookup would not be.
So measure with a realistic read body. A benchmark with tiny reads proves nothing about your service.
- "What about writer starvation?"
-
A steady stream of readers can keep a writer waiting a long time, because new readers keep arriving while old ones leave.
ReentrantReadWriteLockin the default non-fair mode does not let a new reader in if a writer is already at the head of the queue, which reduces this, but a busy read workload still delays writers.Fair mode orders by arrival so a writer is served in turn, with lower throughput.
StampedLockhas the opposite risk: optimistic readers do not block writers at all, so writers do not starve, but readers can retry many times if writes are frequent (the validation keeps failing).So the shape of your workload decides. If a write must take effect quickly, watch writer wait time. If readers must not retry endlessly, limit the optimistic attempts to one or two, then take the real read lock.
- "Is there a simpler alternative for a read-mostly cache?"
-
Often yes: copy-on-write with a volatile reference. Keep the cache as an immutable map in a
volatilefield. Readers just read the field, with no lock at all. A writer builds a modified copy and assigns it with one write.That is ideal when updates are rare (a menu refreshed every minute) and the data is small enough to copy. Reads cost nothing, and the cost lands on the writer.
For larger caches,
ConcurrentHashMapor a caching library such as Caffeine gives fine-grained concurrency with eviction and statistics, with no explicit locks in your code.I reserve
ReadWriteLockfor cases where I must keep several fields consistent together and reads are slow. E3 Q198 compares the options for a hot cache.
Q83 · Scenario. "A cache does if (!map.containsKey(k)) map.put(k, compute(k)) on a ConcurrentHashMap and computes twice. Fix it."
Reveal answer
Strong answer The map is thread-safe, but the sequence is not. Each call (containsKey, put) is atomic by itself. Between the two calls another thread can run the same check, also see "absent", and also compute. This is a check-then-act race, and it is the same bug as the stock check in Q65.
The fix is to give the map the whole decision. map.computeIfAbsent(k, key -> compute(key)) checks and inserts as one atomic step. If several threads ask for the same absent key at once, one runs the function and the others wait and receive the same value. The function runs at most once per key.
The cost of the old code is not only wasted work. If compute has side effects (opens a connection, calls a paid API, loads a big file), you run them several times, and one result may be thrown away or leaked.
Related methods cover other cases: putIfAbsent(k, v) is atomic but computes v before the call, so it does not avoid the double computation. merge(k, v, fn) and compute cover "update from the old value", such as counting.
Two rules for the mapping function. Keep it short and fast, because other threads that need the same bin wait while it runs. And never update the same map from inside it: that throws IllegalStateException: Recursive update (as the demo shows) or, in older versions, can hang.
The cache remembers a value but also a failure mode: if the function throws, nothing is stored and the next caller tries again. For expensive failures consider caching the failure for a short time.
The primer shows this as computeIfAbsent. E3 Q211 is the duplicate-initialisation scenario, Q212 the hang from a recursive function, and Q157 the general check-then-act case.
Picture it Eight threads ask for the same key at the same time.
The setup: loadMenu counts how often it runs and takes 100 ms. Eight threads call it for the key spice-hut, first with containsKey then put, then with computeIfAbsent. A last test calls computeIfAbsent on the same key from inside its own function.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q83ComputeIfAbsent {
static final AtomicInteger computations = new AtomicInteger();
static String loadMenu(String k) { computations.incrementAndGet(); try { Thread.sleep(100); } catch (InterruptedException e) { } return "menu-of-" + k; }
static long run(ConcurrentHashMap<String, String> map, boolean atomic) throws Exception {
computations.set(0);
Thread[] ts = new Thread[8];
for (int i = 0; i < 8; i++) {
ts[i] = new Thread(() -> {
if (atomic) map.computeIfAbsent("spice-hut", Q83ComputeIfAbsent::loadMenu);
else if (!map.containsKey("spice-hut")) map.put("spice-hut", loadMenu("spice-hut"));
});
}
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
return computations.get();
}
public static void main(String[] args) throws Exception {
System.out.println("check-then-act: computed " + run(new ConcurrentHashMap<>(), false) + " times for one key");
System.out.println("computeIfAbsent: computed " + run(new ConcurrentHashMap<>(), true) + " time for one key");
// the trap: the mapping function must not touch the same map
ConcurrentHashMap<Integer, Integer> m2 = new ConcurrentHashMap<>();
try {
m2.computeIfAbsent(5, k -> m2.computeIfAbsent(5, j -> 1));
} catch (IllegalStateException e) {
System.out.println("update the same key inside the function: " + e);
}
}
}Make the invisible visible: Run it.
check-then-act: computed 8 times for one key
computeIfAbsent: computed 1 time for one key
update the same key inside the function: java.lang.IllegalStateException: Recursive updateWhat you see: The check-then-act version computed the same menu 8 times (once per thread). computeIfAbsent computed it once. The recursive update was refused with IllegalStateException: Recursive update.
Why: All eight threads passed containsKey during the 100 ms the first one spent computing. With computeIfAbsent the map held a reservation for the key, so the others waited for the one result.
Check, then put
Eight threads all see "absent" and all compute.
if (!map.containsKey(k)) {
map.put(k, loadMenu(k));
}
return map.get(k);
// loadMenu ran 8 timescomputeIfAbsent
The map runs the function once per key.
return map.computeIfAbsent(k,
key -> loadMenu(key));
// loadMenu ran 1 timeThe shift: The fix is not more locking around the map. It is asking the map to do the check and the insert as one operation.
Land it I replace check-then-put with computeIfAbsent, so the map makes the decision atomically and the expensive function runs once per key.
- "Does computeIfAbsent block other keys while it computes?"
-
Only keys that fall into the same internal bin.
ConcurrentHashMaplocks per bin (the first node of a bucket) while a mapping function for a key in that bin runs. Other bins stay fully available. With a good hash spread, a slow function blocks only a small fraction of the map.It still matters. A 100 ms function can hold up other keys that collide with it, and operations such as
sizeand bulk updates may be affected.The rule is to keep the mapping function short. For something slow, a common pattern is to store a
CompletableFuturein the map:computeIfAbsent(k, key -> supplyAsync(() -> load(key))). The function returns instantly with the future, and the slow work runs outside the bin lock, while all callers share one future.E3 Q212 covers the hang that happens when the function touches the map.
- "What if the function throws or returns null?"
-
If it throws, the exception propagates to the caller and nothing is stored. The next caller will try again, which is right for transient failures and wasteful for permanent ones.
If it returns
null, no mapping is recorded, andcomputeIfAbsentreturns null.ConcurrentHashMapdoes not allow null values at all, so "absent" and "present but null" are never confused.For a cache of "not found" results, store a sentinel (an
Optional.empty()or a dedicated NOT_FOUND object) so you do not recompute a miss on every request.Failures need a policy. For expensive downstream failures, cache the failure briefly to avoid a retry storm: a library such as Caffeine supports different expiry for failures and successes.
- "Why is putIfAbsent not enough here?"
-
Because
putIfAbsent(k, compute(k))evaluatescompute(k)before the call, on every thread, and only then asks the map to keep the first value. All eight threads run the expensive function. The map keeps one result, and seven results are thrown away.It is atomic, so the map stays correct, but it does not save work. Its use is for cheap values that are already built.
The lazy version, where the function runs only if the key is missing, is
computeIfAbsent. Remember that the function is a lambda, so it is not run on the fast path when the key exists.A common confusion is to use
getOrDefault(k, compute(k)), which also computes every time. Anything with the value as a plain argument is computed eagerly. - "When is a cache library better than a ConcurrentHashMap?"
-
As soon as you need any of: a size limit with eviction, expiry by time, refresh in the background, statistics, or loading with failure handling. A bare
ConcurrentHashMapgrows forever, so a cache built on it is a memory leak waiting for a heavy day.Caffeine is the usual choice in Java.
cache.get(key, k -> load(k))has the same once-per-key behaviour ascomputeIfAbsent, plus a maximum size,expireAfterWrite, and hit-rate statistics.I use a plain
ConcurrentHashMapfor a small, fixed set of keys (the restaurants of one city). For anything keyed by user or order, I use a cache library, with a size bound chosen from the heap budget.
Q84. "ConcurrentHashMap versus Collections.synchronizedMap versus Hashtable."
Reveal answer
Strong answer All three are thread-safe maps, built in very different ways, and the difference is how much of the map one operation locks.
Hashtable is the Java 1.0 map. Every method is synchronized on the whole table, so one thread at a time. It rejects null keys and values. It is legacy, and there is no reason to use it in new code.
Collections.synchronizedMap(new HashMap<>()) wraps any map so that every method locks one mutex (the wrapper). It behaves like Hashtable in speed (one lock), but allows nulls because the underlying HashMap does. Iteration is not covered: you must lock the wrapper yourself while you iterate, or you may get ConcurrentModificationException.
ConcurrentHashMap is designed for concurrency. Reads take no lock. Writes lock only the one bin they touch, with compare-and-swap for empty bins (since Java 8 it is no longer segment locking). It rejects null keys and values, offers atomic compound methods (computeIfAbsent, merge, compute), and has iterators that never throw ConcurrentModificationException. They are weakly consistent: they may or may not show changes made after the iterator was created.
The result is a clear ranking. With many threads, ConcurrentHashMap scales and the other two serialise. In the demo it was three times faster than the others.
Two cautions. A concurrent map does not make compound actions atomic unless you use its atomic methods (Q83, Q86). And size() and isEmpty() are estimates while writers are active (E3 Q210).
Pick ConcurrentHashMap for shared maps. Use a synchronized wrapper only if you need null keys or a sorted or linked map under one lock (TreeMap, LinkedHashMap), and use ConcurrentSkipListMap when you need a sorted concurrent map. E3 Q209 explains the internal design.
Picture it Throughput of the three maps with 8 threads, plus null handling and iteration while modifying.
The setup: Eight threads each do 250,000 put and get pairs on distinct keys, so there are 2,000,000 entries. The benchmark runs twice and the second (warm) round is shown. Then each map gets a null key, and iteration plus modification is tried on a synchronized map and a concurrent one.
import java.util.*;
import java.util.concurrent.*;
public class Q84MapKinds {
static long bench(Map<Integer, Integer> m) throws Exception {
Thread[] ts = new Thread[8];
long t0 = System.nanoTime();
for (int t = 0; t < 8; t++) {
int base = t * 250_000;
ts[t] = new Thread(() -> { for (int i = 0; i < 250_000; i++) { m.put(base + i, i); m.get(base + i / 2); } });
ts[t].start();
}
for (Thread t : ts) t.join();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
for (int r = 0; r < 2; r++) {
long h = bench(new Hashtable<>()), s = bench(Collections.synchronizedMap(new HashMap<>())), c = bench(new ConcurrentHashMap<>());
if (r == 1) {
System.out.println("8 threads, 250,000 put + get each (2,000,000 entries):");
System.out.println(" Hashtable: " + h + " ms");
System.out.println(" synchronizedMap(HashMap): " + s + " ms");
System.out.println(" ConcurrentHashMap: " + c + " ms");
}
}
for (Map<String, String> m : List.<Map<String, String>>of(new Hashtable<>(), Collections.synchronizedMap(new HashMap<>()), new ConcurrentHashMap<>())) {
String kind = m.getClass().getSimpleName();
try { m.put(null, "x"); System.out.println(kind + ": null key allowed"); }
catch (NullPointerException e) { System.out.println(kind + ": null key -> NullPointerException"); }
}
// iteration while another thread modifies
Map<Integer, Integer> sm = Collections.synchronizedMap(new HashMap<>(Map.of(1, 1, 2, 2, 3, 3)));
try { for (Integer k : sm.keySet()) sm.put(k + 10, 0); } catch (ConcurrentModificationException e) { System.out.println("synchronizedMap iteration + put: ConcurrentModificationException"); }
Map<Integer, Integer> cm = new ConcurrentHashMap<>(Map.of(1, 1, 2, 2, 3, 3));
int seen = 0; for (Integer k : cm.keySet()) { cm.put(k + 10, 0); seen++; }
System.out.println("ConcurrentHashMap iteration + put: no exception, saw " + seen + " keys, size now " + cm.size());
}
}Make the invisible visible: Run it.
8 threads, 250,000 put + get each (2,000,000 entries):
Hashtable: 499 ms
synchronizedMap(HashMap): 534 ms
ConcurrentHashMap: 161 ms
Hashtable: null key -> NullPointerException
SynchronizedMap: null key allowed
ConcurrentHashMap: null key -> NullPointerException
synchronizedMap iteration + put: ConcurrentModificationException
ConcurrentHashMap iteration + put: no exception, saw 10 keys, size now 13What you see: Hashtable took 499 ms, the synchronized wrapper 534 ms, and ConcurrentHashMap 161 ms, about 3 times faster. Both Hashtable and ConcurrentHashMap refused a null key, and the wrapper over HashMap allowed it. Iterating a synchronized map while writing threw ConcurrentModificationException. The concurrent map did not throw, and its size changed during the loop.
Why: One lock means one thread at a time. Per-bin locking lets 8 writers work in different places at once. The weakly consistent iterator saw 10 keys of the 13 present at the end, which is allowed. Timings are from one run on this machine.
synchronizedMap
One lock for everything. Iteration needs your own lock.
Map<K,V> m = Collections
.synchronizedMap(new HashMap<>());
synchronized (m) { // required
for (K k : m.keySet()) use(k);
}ConcurrentHashMap
Fine-grained locking. Iterators never throw.
Map<K,V> m = new ConcurrentHashMap<>();
for (K k : m.keySet()) {
use(k); // no CME, weakly consistent
}The shift: The concurrent map locks a small piece for a short time, while the wrapper locks the whole map for every call.
Land it I use ConcurrentHashMap for shared maps and its atomic methods for compound updates, and I leave Hashtable to legacy code.
- "Is ConcurrentHashMap still using segments?"
-
No. Java 7 and earlier split the table into 16 segments, each with its own lock. Java 8 replaced that with a finer design. The table is an array of bins. An insert into an empty bin uses a compare-and-swap with no lock. A bin that already has nodes is locked by synchronizing on its first node, only for that bin.
Reads are lock-free, using volatile reads of the table and node fields. Long bins turn into balanced trees once they pass 8 nodes (and the table is large enough), which protects against bad hash functions.
The size is kept in striped counters like
LongAddercells, which is whysize()is a snapshot that may be stale. The concurrency level constructor argument is now only a sizing hint.If an interviewer says "segment locking", the polite correction is "that was Java 7; Java 8 locks per bin". E3 Q209 covers the details.
- "Why does ConcurrentHashMap reject nulls?"
-
Because a null would make some answers ambiguous, and in a concurrent map you cannot resolve the ambiguity with a second call. If
get(k)returns null, does the key have no mapping, or is it mapped to null? In a normal map you could callcontainsKey. In a concurrent one, another thread may change the map between the two calls, so the check would not be reliable.Banning null values removes the ambiguity: null from
getalways means "absent". Banning null keys keeps the hashing simple.The cost is that code moved from
HashMapmay throwNullPointerException. The fix is a sentinel such asOptionalor a constant object for "known empty".The same reasoning is why
computeIfAbsenttreats a null result as "do not record". - "What does weakly consistent iteration mean?"
-
An iterator over a concurrent collection works on the structure as it was when the iterator was created, and may or may not reflect changes made afterwards. It never throws
ConcurrentModificationExceptionand never returns an element twice or skips an existing one that was not changed.In the demo, the loop added keys while iterating and saw 10 keys, even though 13 existed at the end. That is allowed.
The consequence is that you cannot use an iteration as a consistent snapshot of the whole map. If you need "the exact state at one instant", copy under a lock, or use a structure with snapshot semantics (
CopyOnWriteArrayListfor lists).For statistics ("about how many entries") weak consistency is fine. For rules that depend on exact totals it is not. E3 Q210 covers metrics that look impossible.
- "When would I still use a synchronized wrapper?"
-
Four cases come up. You need a null key or value. You need a specific map type that has no concurrent version, such as
LinkedHashMapfor LRU order, where you hold one lock forget-and-reorder. You need to lock several operations together as one unit by synchronizing on the wrapper yourself. Or the map is so lightly used that the single lock is invisible.For a sorted concurrent map use
ConcurrentSkipListMap, which gives navigation methods without a global lock.When I do use a wrapper, I keep the reference to the wrapper private, and I synchronize on it for any multi-step action, so the lock protects the compound operation (Q86).
Q85. "Write a producer–consumer with a BlockingQueue — no wait/notify."
Reveal answer
Strong answer A BlockingQueue is a queue that waits for you. put(x) blocks while the queue is full. take() blocks while it is empty. The waiting, waking and locking are inside the queue, so producers and consumers contain no wait, notify or synchronized at all.
The design has four decisions.
- Pick a bounded queue:
new ArrayBlockingQueue<>(100). The limit gives back-pressure: a fast producer is slowed down when the consumer falls behind, so memory stays bounded. - Producer: loop calling
queue.put(order). It blocks only when the queue is full. - Consumer: loop calling
queue.take()and processing. It blocks when there is nothing to do, using no CPU. - Stop cleanly: send a poison pill, a special marker object that tells the consumer to exit. With several consumers, send one pill per consumer. The alternative is interruption:
consumer.interrupt()makestake()throwInterruptedException.
Choose the queue by behaviour. ArrayBlockingQueue is bounded and array-backed. LinkedBlockingQueue can be bounded and has separate locks for put and take, which helps throughput, but unbounded by default (the danger in Q76). SynchronousQueue has no capacity, a hand-off only. PriorityBlockingQueue orders by priority and is unbounded. DelayQueue releases items after a delay.
Handle the non-blocking variants when needed: offer(x) returns false when full, offer(x, timeout, unit) waits a while, poll(timeout, unit) returns null on timeout. They let a thread do something else rather than block forever.
Interruption is the rule: catch InterruptedException, restore the flag or exit the loop. Do not swallow it.
This is the pattern that replaces hand-written wait/notify (E3 Q164, Q165). E3 Q214 compares the queue types.
Picture it Orders flow from the app to a slow kitchen through a queue of 3.
The setup: The kitchen thread takes an order and spends 100 ms cooking it. Main puts 7 orders as fast as it can into an ArrayBlockingQueue(3), timing each put. After the last order main puts a poison pill.
import java.util.concurrent.*;
public class Q85Producer {
record Order(int id) {}
static final Order POISON = new Order(-1);
public static void main(String[] args) throws Exception {
BlockingQueue<Order> queue = new ArrayBlockingQueue<>(3); // bounded: producers feel back-pressure
Thread kitchen = new Thread(() -> {
try {
while (true) {
Order o = queue.take(); // blocks while empty
if (o == POISON) { System.out.println("kitchen: poison pill, closing"); return; }
System.out.println("kitchen: cooking order " + o.id());
Thread.sleep(100);
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}, "kitchen");
kitchen.start();
for (int i = 1; i <= 7; i++) {
long t0 = System.nanoTime();
queue.put(new Order(i)); // blocks while full
System.out.println("app: queued order " + i + " (put waited " + (System.nanoTime() - t0) / 1_000_000 + " ms)");
}
queue.put(POISON);
kitchen.join();
}
}Make the invisible visible: Run it and read the "put waited" times.
kitchen: cooking order 1
app: queued order 1 (put waited 0 ms)
app: queued order 2 (put waited 0 ms)
app: queued order 3 (put waited 0 ms)
app: queued order 4 (put waited 0 ms)
kitchen: cooking order 2
app: queued order 5 (put waited 97 ms)
kitchen: cooking order 3
app: queued order 6 (put waited 100 ms)
kitchen: cooking order 4
app: queued order 7 (put waited 100 ms)
kitchen: cooking order 5
kitchen: cooking order 6
kitchen: cooking order 7
kitchen: poison pill, closingWhat you see: The first four orders went in at once (one went straight to the kitchen and three filled the queue). Orders 5, 6 and 7 each waited about 100 ms in put, until the kitchen finished one and made room. The pill ended the kitchen loop.
Why: The queue's limit made the producer match the consumer's speed. With an unbounded queue all seven puts would have returned instantly, and a real backlog would sit in memory.
wait and notify
Hand-written lock, loop and signals. Easy to get wrong.
synchronized (buf) {
while (buf.size() == MAX) buf.wait();
buf.add(o);
buf.notifyAll();
}BlockingQueue
The queue does the locking and waiting.
queue.put(o); // waits if full
// consumer
Order o = queue.take(); // waits if emptyThe shift: A blocking queue turns a tricky signalling protocol into two method calls.
Land it I build producer–consumer on a bounded BlockingQueue with put, take and a poison pill, so the queue owns every wait and signal.
- "Why a poison pill and not a boolean flag?"
-
Because the consumer is usually blocked in
take(), waiting for an item. A flag set elsewhere does not wake it. It would stay blocked forever on an empty queue and never read the flag.A poison pill is an item, so
take()returns it like any other. The consumer sees the marker and exits. It also preserves order: all items put before the pill are processed first, so shutdown is orderly.With N consumers, put N pills, one for each. Each consumer takes one and stops. A single pill would stop only one, and then the pill is gone.
The alternative, interruption, is abrupt: it wakes the consumer at once, and items still in the queue are not processed. I use pills for "finish the work, then stop" and interruption for "stop now".
- "What if the consumer is slower than the producer for a long time?"
-
The bounded queue fills, and
putblocks the producer. That is the intended behaviour, but you must decide whether blocking is acceptable for the producer. If the producer is a request thread, blocking makes requests slow.- Block: fine for batch jobs and message consumers; messages wait in the broker.
- Fail fast:
offer(x)returns false and you answer 503 or drop the item, with a metric. - Add consumers: if the consumer is the bottleneck and the work parallelises, run several consumer threads on the same queue.
The queue length is the signal. A queue that sits full is overload, and a queue that is always empty means the consumers are idle. I export it as a gauge and alert on sustained fullness.
- "How do multiple consumers share one queue safely?"
-
They simply all call
take()on the same queue. The queue hands each item to exactly one consumer, so no item is processed twice and no extra locking is needed. This is the work-queue pattern, and it is what a thread pool does inside: workers pulling tasks from a queue.Ordering across consumers is not preserved. If item 1 goes to consumer A and item 2 to consumer B, B may finish first. If order matters per key (all events for one order id), route each key to its own queue, or use a single consumer.
The common simplification is not to write this at all and use an
ExecutorService, whose queue and workers are exactly this design. - "When is a SynchronousQueue the right choice?"
-
When you want a direct hand-off with no buffering.
putblocks until another thread callstakeat the same time, and the other way round. It holds zero items.It is the queue inside
newCachedThreadPool: a task is handed to an idle worker, and if there is none, the pool creates a thread (E3 Q214). It is right when you want a producer to know that a consumer has actually taken the item.It is wrong when you want to absorb bursts, since it has no buffer. For bursts use a bounded
ArrayBlockingQueueand size it from the burst you tolerate.
Q86. "Thread-safe versus atomic: why is a thread-safe collection not enough for compound actions?"
Reveal answer
Strong answer Thread-safe means each single method call on the object is safe to make from many threads at once, and the object never ends up corrupted. Atomic means a whole sequence of steps happens as one indivisible unit. A thread-safe collection gives you the first, not the second.
A compound action is two or more calls whose combined meaning matters: check then add, get then put, size then index, iterate then remove. Each call is safe on its own. Between two calls, another thread can change the collection, so the decision you made from the first call is already stale when the second runs.
The demo below uses Collections.synchronizedList, which is fully thread-safe. Eight threads each ran if (!list.contains("asha")) list.add("asha"). Every call was safe, and the list still ended with "asha" eight times. The check and the add were two atomic steps with a gap between them.
There are three fixes, in order of preference. First, use a method the collection offers that is atomic for that action: putIfAbsent, computeIfAbsent, merge, ConcurrentHashMap.newKeySet().add(x) (add returns false if present), or CopyOnWriteArraySet.add.
Second, hold a lock around the whole sequence. For a synchronized wrapper, synchronized (list) { ... } uses the same lock the wrapper uses, so the whole block is atomic with respect to other calls (this is the documented way).
Third, restructure so there is no shared sequence: give each thread its own collection and merge at the end, or send work to one owning thread through a queue.
The wider lesson is the one from Q65: thread-safe parts do not make a thread-safe whole. The unit of atomicity must match the unit of your rule.
E3 Q157 is the cache version and Q158 lists more cases.
Picture it A synchronized list, eight threads, one rule: add the rider only if not already there.
The setup: The first run does contains then (after a 5 ms pause to widen the gap) add as two separate list calls. The second wraps both inside one synchronized (riders) block.
import java.util.*;
public class Q86ThreadSafeNotAtomic {
static void run(String label, boolean lockWholeAction) throws Exception {
List<String> riders = Collections.synchronizedList(new ArrayList<>());
Thread[] ts = new Thread[8];
for (int i = 0; i < 8; i++) ts[i] = new Thread(() -> {
if (lockWholeAction) {
synchronized (riders) { if (!riders.contains("asha")) riders.add("asha"); }
} else {
if (!riders.contains("asha")) { // check
try { Thread.sleep(5); } catch (InterruptedException e) { }
riders.add("asha"); // act
}
}
});
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
System.out.println(label + ": " + riders);
}
public static void main(String[] args) throws Exception {
run("synchronizedList, separate calls ", false);
run("one synchronized block around both", true);
}
}Make the invisible visible: Run it.
synchronizedList, separate calls : [asha, asha, asha, asha, asha, asha, asha, asha]
one synchronized block around both: [asha]What you see: With separate calls the list contained "asha" eight times. With one lock around both steps it contained her once.
Why: Each call was safe, but all eight threads passed contains before any of them reached add. The 5 ms pause makes this certain in the demo. Without it the bug appears only some of the time, which is what makes it dangerous.
Two safe calls
A gap between the check and the add.
if (!list.contains(x)) {
list.add(x);
}
// each call safe, pair is notOne atomic action
The set itself decides, in one step.
Set<String> s =
ConcurrentHashMap.newKeySet();
boolean added = s.add(x);
// false if it was already thereThe shift: Safe building blocks only compose safely when the structure offers the combined operation as one step.
Land it I remember that thread-safe means each call is safe, not each sequence, so I use the collection's atomic methods or hold one lock around the whole action.
- "What other compound actions fail on thread-safe collections?"
-
Four patterns appear again and again.
- Check then act:
containsKeythenput,isEmptythenremove. - Read then write:
get, add one,putback (a lost update; usemerge(k, 1, Integer::sum)). - Size then index:
if (i < list.size()) list.get(i), which fails if another thread removed an element in between. - Iterate while changing: a loop over a synchronized collection with another thread modifying it, which throws
ConcurrentModificationException.
Each has an atomic alternative in the concurrent classes, or needs one lock around the whole sequence. E3 Q158 gives more examples.
- Check then act:
- "Why does synchronizing on the list work as a fix?"
-
Because the documentation of
Collections.synchronizedListdefines its lock: the wrapper synchronizes on itself (the wrapper object). When you writesynchronized (riders) { ... }you take the very same monitor that every wrapper method takes. While you hold it, no other thread can run any method of the list.So your block is atomic with respect to every other call. This relies on that documented contract. It does not work for an arbitrary "thread-safe" class unless its documentation says what lock it uses.
It also means all code that touches the list must follow the rule where compound actions are concerned. A single place that calls
containsthenaddwithout the lock re-opens the race.I keep the list private to one class, so all compound actions live in that class and the locking rule is enforced in one place.
- "Is an immutable collection a way out?"
-
It removes the problem for reads: nobody can change an immutable list, so no check can become stale, and any number of threads can read it with no locks.
For changes you build a new collection and swap the reference, and that swap is the one shared step, protected by a
volatilefield or anAtomicReferencewith a compare-and-set loop.updateAndGet(old -> newCopyWith(x))is the whole pattern.It suits small, read-heavy data such as a menu, a rate table or a feature-flag set. It is wasteful for big collections that change often, because each change copies.
It also gives a consistent snapshot for free: a reader holds one version for as long as it likes.
- "How do I test for this class of bug?"
-
Write a stress test that runs the compound action from many threads, and assert the invariant at the end. In the demo, "the list has no duplicates" is the invariant.
- Widen the window: add a short sleep or
Thread.yield()between check and act in the test copy, to make the race likely. - Use many threads and a start gate: a latch so all begin together.
- Repeat: a loop of a thousand runs; one run proves little.
The invariant is the valuable part. A bug that violates "stock is never negative" or "no duplicate ids" is found by a test that checks exactly that, and an alert on the same invariant finds it in production.
- Widen the window: add a short sleep or
These questions test whether you can compose asynchronous work without blocking, say which thread runs each step, and keep errors from disappearing.
Q87. "What does CompletableFuture add over Future?"
Reveal answer
Strong answer A plain Future is a receipt you can only wait on: get() blocks, isDone() can be polled, and that is all. A CompletableFuture (Java 8) is a receipt you can also build on, without blocking. It adds five abilities.
- Callbacks:
thenApply,thenAcceptandwhenCompletesay "when it is done, do this", and the calling thread moves on. - Composition:
thenComposechains a dependent async call, andthenCombinejoins two independent results (Q88). - Many at once:
allOfandanyOfwait for a group without a manual loop. - Error pipelines:
exceptionally,handleandwhenCompleteturn failures into fallbacks or logs (Q90). - Time and manual control:
orTimeoutandcompleteOnTimeout(Java 9), and you can complete one yourself withcomplete(value)orcompleteExceptionally(e), which suits wrapping callback-based APIs.
The deeper change is in who waits. With Future, some thread must sit in get() for each result. With CompletableFuture, you describe the pipeline once, and whichever thread finishes the last step runs the rest. No thread is parked just to wait.
There are costs. The pipeline is harder to read and debug than sequential code, stack traces show internals, exceptions arrive wrapped in CompletionException, and it is easy to run the wrong step on the wrong thread (Q89). A failure with no handler disappears (Q92).
With Java 21 virtual threads, plain blocking code on a cheap thread often replaces a pipeline for simple fan-out. CompletableFuture stays valuable for explicit composition, timeouts and fallbacks.
The primer covers it in CompletableFuture. E3 Q189 lists what plain Future lacks, and Q190 to Q194 go deeper.
Picture it The same two QuickBite calls (menu 300 ms, price 250 ms) written both ways.
The setup: With Future, main submits both and blocks on get() twice. With CompletableFuture, main combines the two results with a callback, prints a line immediately, and joins only at the end. A last part completes a future by hand and recovers from a failed one.
import java.util.concurrent.*;
public class Q87CfVsFuture {
static String menu() { sleep(300); return "menu"; }
static int price() { sleep(250); return 499; }
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(4);
long t0 = System.nanoTime();
Future<String> f1 = pool.submit(Q87CfVsFuture::menu);
Future<Integer> f2 = pool.submit(Q87CfVsFuture::price);
System.out.println("Future: main is free for a moment...");
String m = f1.get(); // blocks main
int p = f2.get(); // blocks main again
System.out.println("Future: " + m + " " + p + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms, main blocked on get()");
t0 = System.nanoTime();
long start = t0;
CompletableFuture<String> c1 = CompletableFuture.supplyAsync(Q87CfVsFuture::menu, pool);
CompletableFuture<Integer> c2 = CompletableFuture.supplyAsync(Q87CfVsFuture::price, pool);
CompletableFuture<String> both = c1.thenCombine(c2, (a, b) -> a + " " + b + " rupees")
.whenComplete((v, e) -> System.out.println("CF callback: " + v + " after " + (System.nanoTime() - start) / 1_000_000 + " ms, thread " + Thread.currentThread().getName()));
System.out.println("CF: main did not block, it can do other work now");
both.join();
// things Future cannot do
CompletableFuture<String> manual = new CompletableFuture<>();
new Thread(() -> { sleep(100); manual.complete("completed by hand"); }).start();
System.out.println(manual.get());
System.out.println(CompletableFuture.failedFuture(new RuntimeException("x")).exceptionally(e -> "recovered from " + e.getMessage()).get());
pool.shutdown();
}
}Make the invisible visible: Run it.
Future: main is free for a moment...
Future: menu 499 after 302 ms, main blocked on get()
CF: main did not block, it can do other work now
CF callback: menu 499 rupees after 304 ms, thread pool-1-thread-3
completed by hand
recovered from xWhat you see: Both versions took about 300 ms, since the calls ran in parallel. The difference is in main: with Future it was stuck in get(). With CompletableFuture it printed "main did not block" first, and the callback ran later on pool thread pool-1-thread-3. The last two lines show a manual completion and a recovery.
Why: The callback ran on whichever worker finished last, not on main. The pipeline needed no thread to wait for it.
Future — wait and collect
Main blocks on each get().
var f1 = pool.submit(this::menu);
var f2 = pool.submit(this::price);
String m = f1.get(); // blocks
int p = f2.get(); // blocksCompletableFuture — describe the steps
Say what happens when both are done.
supplyAsync(this::menu, pool)
.thenCombine(
supplyAsync(this::price, pool),
(m, p) -> m + " " + p)
.thenAccept(System.out::println);The shift: A Future makes you wait for results, and a CompletableFuture lets you say what to do with them when they arrive.
Land it I use CompletableFuture when I need to chain, combine, time out or recover, because a plain Future can only be waited on.
- "Does CompletableFuture make the code faster?"
-
Not by itself. Speed comes from running independent work at the same time, which you can do with a plain pool and
invokeAllas well (Q74). Both versions in the demo took about 300 ms.What it improves is how threads are used while waiting. A pipeline needs no thread parked in
get(), so on a busy server fewer threads are idle, and a small pool can serve more concurrent requests.It can also be slower if misused. Chaining many tiny steps adds a small overhead per stage, and running blocking calls in the common pool starves other work (Q89).
So the benefit is structure and thread economy, not magic speed.
- "When is plain blocking code with virtual threads better?"
-
When the logic is a sequence with a little parallel fan-out and you value readability. On a virtual thread you can write
menu(); price(); eta();as ordinary code, and a blocked call costs almost nothing because the thread unmounts. A stack trace then reads top to bottom.A pipeline with seven
thenComposeandhandlestages is much harder to read and debug than the same logic written as plain statements.I still choose
CompletableFuturewhen I need combinators:allOfwith per-call fallbacks,orTimeout, or a library that already returns futures. For all-or-nothing fan-out with cancellation, structured concurrency (Q99) will be the cleaner tool once final.The decision question is whether I need a first-class value that represents the pending result. If not, plain code is simpler.
- "How do I turn a callback API into a CompletableFuture?"
-
Create an empty
CompletableFuture, hand its completion to the callback, and return it. The demo showed the shape:new CompletableFuture<>()completed from another thread withcomplete(value).WrapCallback.javaruns offline// illustrative CompletableFuture<Rider> f = new CompletableFuture<>(); riderApi.find(orderId, rider -> f.complete(rider), // success callback error -> f.completeExceptionally(error)); return f;Always complete it on both paths, success and failure. A callback path that forgets
completeExceptionallyleaves callers waiting forever, which is the hang in Q92. AddorTimeoutas a safety net. - "Is a CompletableFuture cancellable?"
-
Only partly.
cancel(true)completes the future withCancellationException, so dependents see the cancellation. It does not interrupt the thread running the supplier, because the future does not know which thread that is. The task keeps running to the end.That differs from
Future.cancel(true)on a pool task, which does interrupt the worker. For real cancellation of the underlying work you need your own mechanism: a cancellation flag the task checks, or an interruptible resource such as an HTTP call that you can abort when the future is cancelled.Structured concurrency addresses this: a scope that is cancelled interrupts all the threads it forked (Q99). E3 Q195 explains why cancel does not always stop work.
Q88. "thenApply versus thenCompose versus thenCombine."
Reveal answer
Strong answer All three attach a next step to a CompletableFuture. The question each answers is: what does the next step return, and how many futures are involved?
thenApply(fn) is map. The function takes the result and returns a plain value. Use it to transform: price.thenApply(p -> p * 118 / 100). The next stage holds the transformed value.
thenCompose(fn) is flatMap. The function takes the result and returns another CompletableFuture. Use it when the next step is itself asynchronous and depends on the previous result: find the rider for an order, then ask that rider's ETA. If you used thenApply there, you would get a future inside a future, CompletableFuture<CompletableFuture<Integer>>, which is not what you want.
thenCombine(other, fn) joins two independent futures. When both are done, the two-argument function receives both results. Use it for calls that do not depend on each other: price and ETA. They run at the same time, and the total is the slower of the two.
The timing tells you which to choose. Dependent calls (thenCompose) add up: 200 ms plus 300 ms is 500 ms. Independent calls (thenCombine) overlap: the maximum of 300 and 250 is 300 ms.
Mistakes to avoid: using thenCompose for independent calls makes them sequential for no reason. Using thenApply for an async function nests futures. And a thenCombine on futures you created inside a chain, after the first finished, no longer runs in parallel, because the second had not started yet. Start independent futures first, then combine.
Each has an Async version and a thenAcceptBoth / thenRun cousin, covered in Q89. E3 Q190 is the thenApply against thenCompose question.
Picture it Two dependent calls and two independent calls, timed.
The setup: riderFor(orderId) takes 200 ms. etaFor(rider) takes 300 ms and needs the rider. price() takes 250 ms and needs nothing. The program shows the nested type from thenApply, then times thenCompose and thenCombine.
import java.util.concurrent.*;
public class Q88Compose {
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
static CompletableFuture<String> riderFor(int orderId) { return CompletableFuture.supplyAsync(() -> { sleep(200); return "rider-" + orderId; }); }
static CompletableFuture<Integer> etaFor(String rider) { return CompletableFuture.supplyAsync(() -> { sleep(300); return 20 + rider.length(); }); }
static CompletableFuture<Integer> price() { return CompletableFuture.supplyAsync(() -> { sleep(250); return 499; }); }
public static void main(String[] args) {
long t0 = System.nanoTime();
CompletableFuture<CompletableFuture<Integer>> nested = riderFor(7).thenApply(Q88Compose::etaFor);
System.out.println("thenApply with an async function -> " + nested.getClass().getSimpleName() + "<CompletableFuture<Integer>> (a future inside a future)");
int eta = riderFor(7).thenCompose(Q88Compose::etaFor).join();
System.out.println("thenCompose (dependent calls) -> eta " + eta + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms (200 + 300, one after the other)");
t0 = System.nanoTime();
String summary = etaFor("rider-7").thenCombine(price(), (e, p) -> "eta " + e + " min, price " + p).join();
System.out.println("thenCombine (independent calls) -> " + summary + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms (max(300, 250))");
int doubled = CompletableFuture.supplyAsync(() -> 21).thenApply(x -> x * 2).join();
System.out.println("thenApply (plain function) -> " + doubled);
}
}Make the invisible visible: Run it.
thenApply with an async function -> CompletableFuture<CompletableFuture<Integer>> (a future inside a future)
thenCompose (dependent calls) -> eta 27 after 505 ms (200 + 300, one after the other)
thenCombine (independent calls) -> eta 27 min, price 499 after 302 ms (max(300, 250))
thenApply (plain function) -> 42What you see: thenApply with an async function produced a future inside a future. thenCompose took 505 ms (200 plus 300, one after the other). thenCombine took 302 ms (the larger of 300 and 250, side by side).
Why: The ETA call needed the rider, so it had to wait. The price call needed nothing, so it started with the ETA call. Order of dependence decides the timing.
thenApply — returns a value
A plain function. One future in, one value out.
price
.thenApply(p -> p * 118 / 100)
// CompletableFuture<Integer>thenCompose — returns a future
An async step that needs the earlier result.
riderFor(7)
.thenCompose(r -> etaFor(r))
// CompletableFuture<Integer>
// (not a future of a future)The shift: Use thenApply for a plain function, thenCompose for a function that returns a future, and thenCombine for two futures that do not need each other.
Land it I pick by dependence: thenApply to transform, thenCompose when the next call needs the last result, thenCombine when the calls are independent.
- "How do I combine more than two independent futures?"
-
thenCombinetakes two. For three or more you have three options.- Chain combines:
a.thenCombine(b, pair).thenCombine(c, triple). Fine for three, clumsy beyond. allOfthen join each:allOf then joinruns offlineCompletableFuture.allOf(a, b, c) .thenApply(v -> new Result(a.join(), b.join(), c.join()))The
joincalls return at once becauseallOfguarantees they are done.- A collection: for a list of futures, use
allOf(array)then stream and join.
Q91 uses the second form for the three-service checkout. The one thing to remember:
allOfreturnsCompletableFuture<Void>, so you read the individual results from the original futures. - Chain combines:
- "What is flatMap, and why does thenCompose have that shape?"
-
flatMapis the standard name for "apply a function that returns a wrapper, and flatten the result so you do not nest wrappers". The same shape appears inOptional.flatMapandStream.flatMap.For futures it matters because a dependent async call returns a future. Without flattening,
thenApplywould hand you a future of a future, and you would have to unwrap it by hand with anotherthenComposeorjoin.The demo's first line prints exactly that type.
thenComposeremoves one layer, so your chain stays flat and reads as steps.If you ever see
CompletableFuture<CompletableFuture<X>>in a signature, it is almost always athenApplythat should have beenthenCompose. - "What do the Async variants change?"
-
thenApplyAsync,thenComposeAsyncand the others run the step on an executor, not on whichever thread happens to complete the previous stage. Without an argument they use the common pool. With an executor argument they use yours (Q89).Use them when a step is slow or blocking and must not run on the thread that completed the earlier stage, which might be a latency-sensitive caller thread or an I/O event thread.
A cheap, short transformation does not need the Async form, since the hop to another thread costs more than the work.
The result type and meaning are unchanged. The only difference is where the code runs.
- "How are errors passed along these chains?"
-
If any stage fails, every dependent stage is skipped and completes with the same failure, wrapped in a
CompletionException(except the stage that failed directly). Onlyexceptionally,handleandwhenCompleterun on failure (Q90).For
thenCombine, if either input fails, the combined future fails, and the function never runs. If both fail, you see one of the two failures.That is good: a failed rider lookup does not produce a bogus ETA. The danger is the opposite one: a chain without a final handler loses the failure (Q92).
So the discipline is simple. Every pipeline ends with a handler or a
jointhat surfaces the failure.
Q89. "Which thread runs a CompletableFuture callback?"
Reveal answer
The real test Whether you can say it depends on timing and on the method name: a non-async callback runs on the thread that completes the future, or on the caller if the future is already done. Only the Async variants hand the step to an executor.
Strong answer It depends on two things: which method you used, and whether the future was already complete when you attached the callback.
For a non-async method such as thenApply, there are two cases. If the future is still running when you call thenApply, the callback runs on the thread that later completes it, often a pool worker. If the future is already complete, the callback runs immediately on the thread that called thenApply, such as main. You cannot control which one you get, because it depends on timing.
For an Async method such as thenApplyAsync(fn), the callback is submitted to an executor. With no executor argument that is ForkJoinPool.commonPool(). With thenApplyAsync(fn, myExecutor) it is yours.
The source works the same way: supplyAsync(fn) runs on the common pool, supplyAsync(fn, executor) on yours.
Why it matters: the common pool has few threads (cores minus 1, which is 11 on this machine) and is shared with parallel streams. Blocking calls there starve everything else. And a callback that runs on the caller or an I/O thread can block that thread.
The rules I follow: pass your own executor for any blocking or slow step, so the thread is named and bounded. Keep non-async callbacks tiny, since they may run on a thread you do not own. Never block in a callback running on a shared pool.
The primer shows this as Own executor. E3 Q191 compares thenApply and thenApplyAsync, and Q192 shows parallel streams slowed by blocking supplyAsync.
Picture it Print the thread name in every step, in each of the cases.
The setup: A future that finished before the callback was attached, then one still running (it sleeps 300 ms), then supplyAsync with a custom 2-thread pool named mine-. Each callback prints Thread.currentThread().getName().
import java.util.concurrent.*;
public class Q89Threads {
static String me() { return Thread.currentThread().getName(); }
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
ExecutorService mine = Executors.newFixedThreadPool(2, Thread.ofPlatform().name("mine-", 0).factory());
System.out.println("-- already finished before the callback is attached");
CompletableFuture<String> done = CompletableFuture.supplyAsync(() -> "x");
done.join();
done.thenApply(v -> { System.out.println("thenApply on finished future ran on: " + me()); return v; }).join();
done.thenApplyAsync(v -> { System.out.println("thenApplyAsync (no executor) ran on: " + me()); return v; }).join();
done.thenApplyAsync(v -> { System.out.println("thenApplyAsync(mine) ran on: " + me()); return v; }, mine).join();
System.out.println("-- still running when the callback is attached");
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> { sleep(300); System.out.println("supplyAsync body ran on: " + me()); return "y"; });
CompletableFuture<String> cb = slow.thenApply(v -> { System.out.println("thenApply (attached early) ran on: " + me()); return v; });
cb.join();
System.out.println("-- supplyAsync with my own executor");
CompletableFuture.supplyAsync(() -> me(), mine).thenAccept(n -> System.out.println("body on " + n + ", callback on " + me())).join();
System.out.println("common pool parallelism: " + ForkJoinPool.commonPool().getParallelism());
mine.shutdown();
}
}Make the invisible visible: Run it.
-- already finished before the callback is attached
thenApply on finished future ran on: main
thenApplyAsync (no executor) ran on: ForkJoinPool.commonPool-worker-1
thenApplyAsync(mine) ran on: mine-0
-- still running when the callback is attached
supplyAsync body ran on: ForkJoinPool.commonPool-worker-1
thenApply (attached early) ran on: ForkJoinPool.commonPool-worker-1
-- supplyAsync with my own executor
body on mine-1, callback on main
common pool parallelism: 11What you see: On the already-finished future, thenApply ran on main. thenApplyAsync ran on ForkJoinPool.commonPool-worker-1, or on mine-0 when I passed my executor. For a still-running future, the callback ran on the same common-pool worker that completed it. The common pool has 11 threads here.
Why: A non-async callback does not hop threads. It runs wherever the completion happens. The last line shows that the body ran on mine-1 but the callback attached afterwards ran on main, because the future had already finished by then.
No executor named
Common pool, shared with parallel streams.
supplyAsync(() -> callPayments())
.thenApply(r -> parse(r));
// ForkJoinPool.commonPool-worker-1
// blocking here starves other workYour own executor
A named, bounded pool you control.
supplyAsync(() -> callPayments(), io)
.thenApplyAsync(r -> parse(r), io);
// payments-io-0 ...
// the common pool stays freeThe shift: Without an executor argument the work lands on a shared pool, and with one it lands where you chose.
Land it I say a plain thenApply runs on whichever thread completes the future, so I pass my own executor to anything slow or blocking.
- "Why does it matter that the common pool is shared?"
-
Because it is one pool for the whole JVM: parallel streams,
supplyAsyncwithout an executor, and some library code all use it. It has only cores minus 1 threads (11 here).If a
supplyAsyncdoes a 2-second HTTP call on it, that thread is unavailable for 2 seconds. Eleven such calls take all the threads, and every parallel stream in the application now waits. Unrelated code gets slow, and CPU stays low because the threads are idle, waiting (E3 Q192).That is why blocking work needs its own executor. A dedicated, named I/O pool contains the damage: if payments are slow, only the payments pool fills.
With virtual threads, an executor from
newVirtualThreadPerTaskExecutoris a good choice for blocking steps, as it needs no size. - "Can a callback run on the thread that called thenApply?"
-
Yes, when the future was already complete at that moment. The callback runs at once, inside the
thenApplycall, on the caller's thread. The demo's first line shows it:main.That has two consequences. A slow callback blocks the caller, and an exception in it is stored in the returned future, not thrown at the call site.
It also means the same code can run on different threads in different runs. A fast service call may finish before you attach the callback (callback on the caller), and a slow one after (callback on the worker). Tests that pass on one path and fail on the other are a known source of flaky behaviour.
If the thread matters for correctness, use the Async form with an explicit executor, which makes the thread predictable.
- "Does thread identity matter for ThreadLocal or context?"
-
Yes, a lot. A
ThreadLocalvalue (a request id, a security context, a transaction) belongs to one thread. A callback that runs on another thread does not see it. Logging that relies on an MDC loses the request id in the callback.The fixes: capture the context into a local variable before the async call and pass it in, wrap the executor so that it copies the context to each task (Spring and Micrometer offer context-propagating decorators), or use a
ScopedValuewith structured concurrency, which flows into forked subtasks (Q98).It is a common production bug: after adding
supplyAsync, logs lose the trace id and the security principal is null. - "How do I make a callback run on a specific thread, like a UI or event-loop thread?"
-
Pass that thread's executor to the Async variant. If the framework offers an
Executorfor its event thread, usethenApplyAsync(fn, eventLoopExecutor). If you only have the thread, a small executor that posts a task to it will do.In a single-threaded model (a UI, Netty, a game loop) the rule is stricter: never block, and return to the owner thread to touch its state.
In a typical Spring MVC service there is no special thread to return to, and any pool thread is fine for the callback as long as it is not the shared common pool.
Q90. "exceptionally versus handle versus whenComplete."
Reveal answer
Strong answer All three run when a stage ends, but they differ in when they run, what they receive, and whether they can replace the outcome.
| Method | Runs when | Receives | Can change the result? |
|---|---|---|---|
exceptionally(fn) | Only on failure | The exception | Yes: returns a fallback value |
handle(fn) | Always | Value and exception (one is null) | Yes: returns a new value for both cases |
whenComplete(fn) | Always | Value and exception | No: observes only, the result passes through |
Use exceptionally for a simple fallback: "if the rider service fails, answer -1". Use handle when you need one place that deals with both outcomes, such as turning either a value or a failure into a response object. Use whenComplete for side effects that must not change anything: logging, metrics, releasing a resource.
A subtle point is which exception you receive. When a stage fails because an earlier stage threw, the exception is wrapped in CompletionException, and the real failure is its getCause(). The demo prints this. When a future is failed directly with completeExceptionally(e), you receive e unwrapped. Handlers should unwrap defensively.
whenComplete does not recover. After it, the future still has the same failure, and join() still throws. If you want to log and recover, chain whenComplete then exceptionally, or use one handle that logs and returns a fallback.
If the handler itself throws, the new future fails with that exception, so keep handlers simple.
The primer builds this into Handle errors. E3 Q193 is the matching interview question, including which exception type you actually catch.
Picture it One failing and one succeeding future, through each handler.
The setup: failing() throws an IllegalStateException inside supplyAsync. ok() returns 30. Each handler is attached to both, and the program prints the exception type each handler receives. A last future is failed directly.
import java.util.concurrent.*;
public class Q90Handlers {
static CompletableFuture<Integer> failing() { return CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("rider service down"); }); }
static CompletableFuture<Integer> ok() { return CompletableFuture.supplyAsync(() -> 30); }
public static void main(String[] args) {
System.out.println("exceptionally on failure: " + failing().exceptionally(e -> { System.out.println(" e is " + e.getClass().getSimpleName() + " -> cause " + e.getCause()); return -1; }).join());
System.out.println("exceptionally on success: " + ok().exceptionally(e -> -1).join() + " (handler never ran)");
System.out.println("handle on failure: " + failing().handle((v, e) -> e != null ? "fallback(" + e.getCause().getMessage() + ")" : "value " + v).join());
System.out.println("handle on success: " + ok().handle((v, e) -> e != null ? "fallback" : "value " + v).join());
CompletableFuture<Integer> w = failing().whenComplete((v, e) -> System.out.println(" whenComplete saw v=" + v + " e=" + (e == null ? null : e.getClass().getSimpleName())));
try { w.join(); } catch (CompletionException e) { System.out.println("whenComplete does not recover: join threw " + e.getClass().getSimpleName() + " / " + e.getCause().getMessage()); }
CompletableFuture<Integer> direct = new CompletableFuture<>();
direct.completeExceptionally(new IllegalStateException("set directly"));
direct.exceptionally(e -> { System.out.println("directly failed future: e is " + e.getClass().getSimpleName() + " (not wrapped)"); return 0; }).join();
}
}Make the invisible visible: Run it.
e is CompletionException -> cause java.lang.IllegalStateException: rider service down
exceptionally on failure: -1
exceptionally on success: 30 (handler never ran)
handle on failure: fallback(rider service down)
handle on success: value 30
whenComplete saw v=null e=CompletionException
whenComplete does not recover: join threw CompletionException / rider service down
directly failed future: e is IllegalStateException (not wrapped)What you see: exceptionally received a CompletionException whose cause was the real error, and its fallback -1 became the result. On success it never ran. handle ran in both cases. whenComplete saw the failure but changed nothing, so join() still threw. The future failed directly gave an unwrapped IllegalStateException.
Why: exceptionally and handle return a new value, which replaces the failure. whenComplete is an observer, so the original outcome flows through.
exceptionally — failure only
A fallback value when something went wrong. Success passes through.
eta.exceptionally(e -> {
log.warn("eta failed", e);
return -1; // fallback
});handle — both outcomes
One function sees the value or the failure and returns a result.
eta.handle((v, e) -> e != null
? Eta.unknown()
: Eta.of(v));
// always runs, always returnsThe shift: Use exceptionally when only the failure needs a decision, and handle when one function should shape the answer either way.
Land it I use exceptionally for a fallback, handle when one place must deal with both outcomes, and whenComplete only to observe, remembering it never recovers.
- "Which exception do I actually catch, CompletionException or the original?"
-
It depends on the path, so write handlers that cope with both. If the failure happened in the stage itself or in an earlier stage, a later handler receives a
CompletionExceptionwith the original as its cause. If the future was completed withcompleteExceptionally(e)and the handler is attached directly to it, you receiveeitself.A small helper unwraps it safely: while the throwable is a
CompletionExceptionorExecutionExceptionwith a cause, step to the cause.Unwrap.javaruns offline// illustrative static Throwable root(Throwable t) { while ((t instanceof CompletionException || t instanceof ExecutionException) && t.getCause() != null) t = t.getCause(); return t; }Then
root(e) instanceof TimeoutExceptionworks whichever path it took. E3 Q193 covers the same point. - "How do I log a failure and still recover?"
-
Use one
handlethat does both, or two steps in order.One handle:
one handle stepruns offlinehandle((v, e) -> { if (e != null) { log.warn("eta failed", e); return FALLBACK; } return v; })Two steps:
two stepsruns offline.whenComplete((v, e) -> { if (e != null) log.warn("eta failed", e); }) .exceptionally(e -> FALLBACK)
The second reads well and keeps logging separate from recovery. Either way, log the whole exception object, not only its message, so the cause chain and stack trace are kept.
Add a metric in the same place. A fallback that fires silently is a degraded service you do not know about, so count it.
- "What happens to a handler's own exception?"
-
If the function you pass to
exceptionallyorhandlethrows, the future it returns fails with that new exception, wrapped in aCompletionExceptionfor later stages. The original failure is lost unless you attach it withaddSuppressedor include it as the cause.So handlers should be small and safe. A handler that parses, calls another service or does I/O can fail in the very moment you are trying to recover.
If the fallback is itself risky, make it another async step with its own handler, as in
exceptionallyCompose(Java 12), which lets the fallback return a future. - "Where in the chain should I put the handler?"
-
As late as possible for a general fallback, and early for a specific one. The handler covers every earlier stage in the chain. A handler at the end catches any failure above it, which is the safety net. A handler right after one risky call gives that call its own fallback and lets the rest of the chain continue.
In the checkout, each service call has its own fallback (an ETA falls back to "about 30 min"), and the end of the chain has a final handler that logs anything unexpected.
A handler also resets the failure state. After
exceptionallyreturns a value, later stages run normally. AfterwhenComplete, they still see the failure.
Q91 · Scenario. "Call three services in parallel, combine the results, and enforce a two-second overall timeout with a fallback."
Reveal answer
Strong answer Start all three calls first so they run at the same time. Give each call its own fallback on timeout. Combine the results into one record. Add one hard overall limit as a safety net. Run everything on your own named executor.
- Start the three futures:
supplyAsync(menuCall, io),supplyAsync(priceCall, io),supplyAsync(etaCall, io). Start them before combining so none waits for another. - Per-call fallback:
.completeOnTimeout(fallback, 2, SECONDS)on the future that may be slow (the rider ETA), so a slow service gives a default, not a failure. - Combine:
thenCombinetwice, orallOfand then read each withjoin(), into aCheckoutrecord. - Hard limit:
.orTimeout(3, SECONDS)on the combined future. If something else goes wrong, the caller gets aTimeoutExceptionand not a hang. - Handle the rest: a final
handleorexceptionallyto turn failures into a degraded response and a log line.
Which calls may fall back is a product decision. An ETA can be "about 30 min". A price cannot be guessed, so if price fails the whole checkout should fail. Menu may be served from a cache. Write that down, because the fallback rules are the design.
Know what timeouts do not do. completeOnTimeout and orTimeout complete the future, but the slow task keeps running on its thread (Q73). In the demo the 5-second rider call kept its worker busy until it ended, so size the pool for that or make the call interruptible with its own client timeout.
Timeout values must fit together: each call's own client timeout, then the per-call fallback, then the overall limit, with the overall limit largest.
The primer builds this as Fan-out with timeout. E3 Q194 asks the same question.
Picture it A checkout with menu (300 ms), price (250 ms) and a rider ETA that is either fast or very slow.
The setup: Three futures on a named 3-thread pool. The ETA future has completeOnTimeout("about 30 min", 2, SECONDS). The results are combined into a Checkout record, with an overall orTimeout(3, SECONDS). It runs once with a 350 ms rider and once with a 5,000 ms rider.
import java.util.concurrent.*;
public class Q91Checkout {
record Checkout(String menu, int priceCents, String eta) {}
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
static Checkout checkout(ExecutorService io, int riderMs) {
CompletableFuture<String> menu = CompletableFuture.supplyAsync(() -> { sleep(300); return "menu-v12"; }, io);
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> { sleep(250); return 49900; }, io);
CompletableFuture<String> eta = CompletableFuture.supplyAsync(() -> { sleep(riderMs); return "22 min"; }, io)
.completeOnTimeout("about 30 min", 2, TimeUnit.SECONDS); // per-call fallback
return menu.thenCombine(price, (m, p) -> new Object[]{m, p})
.thenCombine(eta, (mp, e) -> new Checkout((String) mp[0], (Integer) mp[1], e))
.orTimeout(3, TimeUnit.SECONDS) // hard overall limit
.join();
}
public static void main(String[] args) {
try (ExecutorService io = Executors.newFixedThreadPool(3, Thread.ofPlatform().name("checkout-io-", 0).factory())) {
for (int riderMs : new int[]{350, 5000}) {
long t0 = System.nanoTime();
Checkout c = checkout(io, riderMs);
System.out.println("rider takes " + riderMs + " ms -> " + c + " in " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
}
}
}Make the invisible visible: Run it.
rider takes 350 ms -> Checkout[menu=menu-v12, priceCents=49900, eta=22 min] in 362 ms
rider takes 5000 ms -> Checkout[menu=menu-v12, priceCents=49900, eta=about 30 min] in 2000 msWhat you see: With a normal rider the checkout finished in 362 ms (the slowest call, 350 ms, plus small overhead). With a 5-second rider it returned at 2,000 ms with the fallback ETA "about 30 min", and menu and price were real.
Why: The three calls overlapped, so the total is the maximum, not the sum of 900 ms. The fallback cut the wait at the limit. The slow rider call itself kept running in the background, and the program exits about 3 seconds later when the pool closes. That is the cost that timeouts do not remove.
One after another
300 + 250 + 350 ms, and no limit.
String menu = menu();
int price = price();
String eta = eta();
// about 900 ms, hangs if eta hangsParallel with limits
Overlap, per-call fallback, hard cap.
var eta = supplyAsync(this::eta, io)
.completeOnTimeout(
"about 30 min", 2, SECONDS);
// combine, then .orTimeout(3, SECONDS)The shift: The pattern replaces a sum of delays with a maximum, and replaces a possible hang with a decision you made in advance.
Land it I start the calls together, give the optional ones a timeout fallback, combine them into a record, and cap the whole thing with orTimeout.
- "What is the difference between orTimeout and completeOnTimeout?"
-
orTimeout(t, unit)makes the future fail withTimeoutExceptionif it is not complete in time. Use it as a hard limit, when no sensible default exists.completeOnTimeout(value, t, unit)makes the future succeed with a default value. Use it when a degraded answer is acceptable (an ETA estimate, a cached menu).Both arrived in Java 9. They work by scheduling a task on an internal timer thread, so the timer itself costs almost nothing, and it does not hold a worker while waiting.
Neither stops the underlying work. If the slow task owns a database connection, it still holds it. So I also set a client-level timeout on the HTTP or database call, a few hundred milliseconds beyond the future's.
- "How do I wait for all three without blocking a thread?"
-
Use
allOfand athenApplythat reads the results. No thread is parked while the calls run.AllOfShape.javaruns offline// illustrative CompletableFuture.allOf(menu, price, eta) .thenApply(v -> new Checkout( menu.join(), price.join(), eta.join())) .orTimeout(3, TimeUnit.SECONDS);The
join()calls insidethenApplynever block, becauseallOfcompletes only after all three are done.If any of the three fails,
allOffails too, once all are done. For partial results, give each future its ownhandlebeforeallOf, so each one always completes normally with a value or a marker. - "What if price fails but menu and ETA succeed?"
-
That depends on the business rule, and the code should make the rule visible. For checkout, a missing price means the order cannot be placed, so the whole result should fail with a clear error and a 503 or 502 to the client.
For a page that only displays information, a missing price might show "price unavailable". In that case, give
priceahandlethat returns anOptional.empty()and let the record carry an optional price.I encode it in the type. A
Checkoutwithint priceCentssays price is required. A record withOptional<Integer>says it is allowed to be missing. The compiler then reminds every reader of the rule. - "Would structured concurrency or virtual threads make this simpler?"
-
Probably, once structured concurrency is final. With virtual threads and
StructuredTaskScope(preview in Java 25), you fork three subtasks in a scope, calljoin(), and read the results. If one fails, the scope cancels the others automatically and propagates the error (Q99).A timeout is a
Joineror configuration setting on the scope, and the code reads like plain sequential code, with normal try/catch and clear stack traces.The
CompletableFutureversion has finer control over per-call fallbacks, and works on every Java 8 or later runtime, with no preview flag. Today in production code I useCompletableFuture, and I would move this method to structured concurrency when the API is final.
Q92 · Scenario. "A CompletableFuture chain fails, but nothing is logged. Why?"
Reveal answer
Strong answer Because a CompletableFuture never logs a failure itself. When a stage throws, the exception is stored inside the future, and every dependent stage is skipped. If nobody calls join(), get() or a handler on the end of the chain, nobody ever looks at the stored exception. The failure is complete, silent and invisible.
This is the same mechanism as the submit trap in Q72, with more places to lose it. The usual forms are a fire-and-forget chain such as supplyAsync(...).thenAccept(...) whose result is dropped, a chain that returns the future to a caller who ignores it, and a handler placed before a later risky stage that therefore does not cover it.
There is a second, related failure that also leaves no log line: a future that is never completed. A callback-based wrapper that completes only on success leaves the future pending forever, so waiters hang instead of failing.
The fix has four parts.
End every chain with a terminal handler:
a terminal handlerruns offline.whenComplete((v, e) -> { if (e != null) log.error("checkout failed", e); })or a
handlethat produces a fallback.- Return or join the future: someone must own the result, and that owner must handle the failure.
- Add timeouts:
orTimeoutso a never-completing future fails and is logged by your handler. - Complete on both paths: in wrappers, always call
completeorcompleteExceptionally.
A convention helps teams: a small utility such as fireAndLog(future, "name") that attaches the log handler, so no one writes a bare fire-and-forget chain.
The primer shows this as Handle errors, and the incident in the primer is exactly this bug: a spinner forever. E3 Q193 covers the handler types.
Picture it The same failing chain three ways: no handler, a terminal handler, and a future that never completes.
The setup: supplyAsync throws "price service 500", and a thenAccept follows. The first chain has no handler. The second ends with whenComplete that logs. The third is a future nobody completes, waited on with a timeout.
import java.util.concurrent.*;
public class Q92Silent {
static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } }
public static void main(String[] args) throws Exception {
System.out.println("-- fire and forget, no handler");
CompletableFuture<Void> lost = CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("price service 500"); })
.thenAccept(v -> System.out.println("never printed"));
sleep(500);
System.out.println("500 ms later: nothing logged; lost.isCompletedExceptionally() = " + lost.isCompletedExceptionally());
System.out.println("-- the same chain with a terminal handler");
CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("price service 500"); })
.thenAccept(v -> System.out.println("never printed"))
.whenComplete((v, e) -> { if (e != null) System.out.println("LOGGED: " + e.getCause()); });
sleep(300);
System.out.println("-- and a hang: nobody ever completes this future");
CompletableFuture<String> forever = new CompletableFuture<>();
try { forever.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { System.out.println("get(500 ms) -> TimeoutException; orTimeout would have failed it for everyone"); }
}
}Make the invisible visible: Run it.
-- fire and forget, no handler
500 ms later: nothing logged; lost.isCompletedExceptionally() = true
-- the same chain with a terminal handler
LOGGED: java.lang.IllegalStateException: price service 500
-- and a hang: nobody ever completes this future
get(500 ms) -> TimeoutException; orTimeout would have failed it for everyoneWhat you see: In the first case, 500 ms passed with nothing printed anywhere, although the future was completed exceptionally. In the second, the terminal handler printed the real cause at once. The third waited and the timed get reported a TimeoutException.
Why: Nothing in the first chain asked for the outcome. The exception sat in the future until the garbage collector removed it. In production this is a customer staring at a spinner while the logs are clean.
Land it I end every chain with a handler that logs, I add a timeout so a never-completed future fails loudly, and I treat a clean log with a stuck request as a lost exception.
- "How can I find lost failures in an existing codebase?"
-
Search for the shapes that lose them.
- Fire-and-forget: grep for
supplyAsync,runAsyncandthenAcceptwhose result is not assigned, returned or joined. - Chains without a terminal handler: any chain whose last call is
thenApply,thenAcceptorthenRun. - Wrappers that complete on one path: code that creates a
new CompletableFuture<>()and callscompletein only one branch.
Static analysis helps: IntelliJ and Error Prone can flag ignored return values of futures. At runtime, a symptom list is "requests that hang, with a clean log" and thread dumps full of threads WAITING in
CompletableFuture.get.Add a test that forces the downstream to fail and asserts that a log line or a fallback appears. That test would have caught the incident.
- Fire-and-forget: grep for
- "Is there a way to log all unhandled failures automatically?"
-
Not built in. A plain
CompletableFuturehas no global "unobserved exception" hook, unlike some other languages, so the discipline must be yours.Two practical helpers. First, a wrapper method for fire-and-forget work, with this signature:
the logging wrapper signatureruns offlinestatic <T> CompletableFuture<T> logged(CompletableFuture<T> f, String name)that returns
f.whenComplete(...)with logging, and a team rule to use it. Second, wrap your executor so that tasks submitted through it are tracked and any failure is logged.Frameworks help: Spring's
@Asyncmethods return futures and use anAsyncUncaughtExceptionHandlerforvoidmethods, which logs by default (E4).I rely on the convention plus review, because a hook cannot know whether a failure was handled elsewhere.
- "What does a hung request look like in a thread dump?"
-
It depends on who is waiting. If a request thread called
future.get()orjoin()without a timeout, that thread shows WAITING inCompletableFuture$Signaller.blockorUnsafe.park, with your code a few frames below.If the caller is non-blocking (it returned a future to a framework), there may be no waiting thread at all. The request is just an object waiting to be completed, and the dump shows idle pool threads while a request is stuck. That is the hardest case, because the evidence is a missing thread.
Both point to the same fix: a timeout. With
orTimeout, a never-completing future fails after the limit, the handler logs it, and the client gets an error instead of a spinner. - "How do I test that failures are not lost?"
-
Inject a failing dependency and check the observable result: a log line, a metric, an error response or a fallback. A test that only checks the success path will pass while the failure path silently drops errors.
- Make the call fail: a stub that throws or returns a failed future.
- Wait with a deadline:
future.get(2, SECONDS)orjoinafterorTimeout, so the test cannot hang. - Assert on the outcome: the logged event (a test appender), the fallback value, or the failed state with the expected cause.
Using a direct executor in tests (
Runnable::run) makes async code run on the test thread and removes sleeps, so the test is fast and deterministic.
Q93. "join() versus get()."
Reveal answer
Strong answer Both wait for a CompletableFuture and return its value. They differ in the exceptions they throw, and that decides where each fits.
get() comes from Future. It declares checked exceptions: InterruptedException (the waiting thread was interrupted) and ExecutionException (the computation failed, with the real error as its cause). There is also get(timeout, unit) which adds TimeoutException.
join() belongs to CompletableFuture. It throws only unchecked exceptions: CompletionException (wrapping the failure, with the real error as its cause) and CancellationException if the future was cancelled. It does not throw InterruptedException, and it has no timeout version.
Because it is unchecked, join() is the one you can use inside a lambda or a stream, where checked exceptions are a nuisance: futures.stream().map(CompletableFuture::join).toList(). get() fits ordinary methods where you want to handle interruption and timeouts explicitly.
Two practical points. For timeouts, use get(timeout), or call orTimeout on the future and then join(). And join() ignores interruption of the waiting thread: if the thread is interrupted while in join(), it keeps waiting and the flag stays set. That makes it a poor choice where cancellation of the waiting thread matters.
The same effect with different wrappers: get() gives ExecutionException and join() gives CompletionException, and both hold the original failure as the cause. Unwrap with getCause() in both.
A rule I follow: in application code that can be interrupted, prefer get(timeout). Inside streams and after an allOf (when you know the future is done), use join(). And never call either on an event-loop thread.
E3 Q193 covers the exception types you catch.
Picture it Each call on a failed future, a cancelled future, an interrupted waiter, and in a stream.
The setup: A future that throws IllegalArgumentException. A cancelled future. A thread blocked in get() that is interrupted. Then a stream of three futures joined with CompletableFuture::join.
import java.util.concurrent.*;
public class Q93JoinGet {
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> { throw new IllegalArgumentException("bad order"); });
try { f.join(); } catch (Exception e) { System.out.println("join(): " + e.getClass().getName() + " -> cause " + e.getCause()); }
try { f.get(); } catch (Exception e) { System.out.println("get(): " + e.getClass().getName() + " -> cause " + e.getCause()); }
CompletableFuture<Integer> c = new CompletableFuture<>();
c.cancel(true);
try { c.join(); } catch (Exception e) { System.out.println("join() on cancelled: " + e.getClass().getName()); }
try { c.get(); } catch (Exception e) { System.out.println("get() on cancelled: " + e.getClass().getName()); }
Thread t = new Thread(() -> {
try { new CompletableFuture<Integer>().get(); } catch (InterruptedException e) { System.out.println("get() interrupted: InterruptedException (checked)"); } catch (ExecutionException e) { }
});
t.start(); Thread.sleep(100); t.interrupt(); t.join();
System.out.println("getNow(-1) on unfinished: " + new CompletableFuture<Integer>().getNow(-1));
// join() inside a lambda: no checked exceptions
System.out.println(java.util.List.of(1, 2, 3).stream().map(i -> CompletableFuture.supplyAsync(() -> i * 10)).map(CompletableFuture::join).toList());
}
}Make the invisible visible: Run it.
join(): java.util.concurrent.CompletionException -> cause java.lang.IllegalArgumentException: bad order
get(): java.util.concurrent.ExecutionException -> cause java.lang.IllegalArgumentException: bad order
join() on cancelled: java.util.concurrent.CancellationException
get() on cancelled: java.util.concurrent.CancellationException
get() interrupted: InterruptedException (checked)
getNow(-1) on unfinished: -1
[10, 20, 30]What you see: On the failed future, join() threw CompletionException and get() threw ExecutionException, with the same cause. Both threw CancellationException on the cancelled one. An interrupted get() raised InterruptedException. getNow(-1) returned the default at once. The stream line shows join inside map, which compiles with no try/catch.
Why: The two methods report the same failure in two wrapper types, one checked and one not. The stream example is the reason join exists.
get() — checked
Handle interruption and wrapping explicitly.
try {
return f.get(2, SECONDS);
} catch (ExecutionException e) {
throw unwrap(e);
} catch (InterruptedException
| TimeoutException e) { ... }join() — unchecked
Fits lambdas and streams. No timeout, no interruption.
List<Integer> all = futures.stream()
.map(CompletableFuture::join)
.toList();
// CompletionException on failureThe shift: get() makes you handle the waiting problems, and join() trades that for code you can drop into a lambda.
Land it I use join() inside streams and after allOf, and get(timeout) where interruption and timeouts need handling.
- "Why does join() ignore interruption?"
-
It was designed for use inside lambdas and callbacks where an
InterruptedExceptioncannot be thrown, so it waits uninterruptibly: if the thread is interrupted,join()keeps waiting, and it re-sets the interrupt flag when it returns.The result is that a thread blocked in
join()cannot be cancelled byinterrupt(). During a shutdown, a worker stuck injoin()on a slow future holds up the whole stop (E3 Q179 shows a similar problem).The fix is a timeout. Put
orTimeouton the future beforejoin(), so the wait always ends. Or useget(timeout), which responds to interruption. - "What is getNow and when is it useful?"
-
getNow(default)returns the result if the future is already complete, and the default if it is not. It never blocks, and the demo shows it returning -1 on a future that nobody had completed.It is useful for polling and opportunistic reads: "if the cache refresh has finished use it, else use the old one". It is also handy after
allOf, as a cheap way to read a value you know is ready, thoughjoin()expresses that more clearly.Related non-blocking checks:
isDone(),isCompletedExceptionally()and (Java 19)state(),resultNow()andexceptionNow(). - "Is it OK to call join() inside a CompletableFuture callback?"
-
It is allowed, but it is usually a smell. Calling
join()on another future insidethenApplyblocks the thread that runs the callback until the other future finishes. On a small pool, enough of these can use up all the threads waiting for futures that need those same threads: a starvation deadlock.The fix is to compose instead: use
thenComposefor a dependent future, orthenCombinefor an independent one (Q88). They continue when the other future completes, and no thread waits.The exception is
join()on a future that is known to be done, such as inside athenApplyafterallOf, where it returns immediately. - "How do I convert a get() failure into a clean domain exception?"
-
Catch
ExecutionException, look at the cause, and rethrow in a way that keeps meaning.- Runtime exceptions and errors: rethrow as they are, so callers see the real type.
- Known checked exceptions: translate to your domain exception, with the original as the cause.
- Everything else: wrap in a generic unchecked exception that names the operation and keeps the cause.
Handle
InterruptedExceptionseparately: restore the flag withThread.currentThread().interrupt()and exit or throw a cancellation exception. Never swallow it.One helper that does this, used everywhere, keeps the rest of the code tidy and consistent.
These questions cover the newest part of Java concurrency: cheap threads, what still goes wrong with them, and how to choose between all the tools in this chapter.
Q94. "What is a virtual thread, and how does it differ from a platform thread?"
Reveal answer
Strong answer A platform thread is a thin wrapper over an operating-system thread. It has its own large stack (about 1 MB reserved), the OS schedules it, and a machine can hold only a few thousand. A virtual thread (final in Java 21) is an ordinary Java object that the JVM schedules itself. It has a small stack that lives on the heap and grows as needed, so you can have millions.
The trick is mounting. The JVM keeps a small pool of platform threads called carriers (by default one per core). A virtual thread runs by being mounted on a carrier. When it hits a blocking call (sleep, socket read, lock, queue take), the JVM copies its stack to the heap and unmounts it, freeing the carrier to run another virtual thread. When the wait ends, the virtual thread is mounted again, on any carrier.
That gives the "one thread per task" programming model with the cost profile of async code. A blocked virtual thread costs memory for its stack frames and almost no CPU, not a whole OS thread.
What stays the same: it is a Thread (same API: start, join, interrupt, ThreadLocal), runs ordinary blocking code, and shows up in debuggers and (via jcmd Thread.dump_to_file) in dumps.
What differs: virtual threads are always daemon, their priority is fixed at normal, they should not be pooled (create one per task), they are cheap but not free, and they do not make CPU-bound work faster. They shine for work that mostly waits: HTTP calls, database queries, queues.
Create them with Thread.ofVirtual().start(r), Thread.startVirtualThread(r) or Executors.newVirtualThreadPerTaskExecutor().
The primer builds this in Virtual threads. E3 Q215 explains what a virtual thread is, and E2 Modern Concurrency shows what one is made of.
Picture it Inspect one virtual thread, then create 100,000 of them, then compare with platform threads.
The setup: One named virtual thread prints itself and its properties. Then 100,000 virtual threads each sleep 500 ms. Then 2,000 platform threads (through a cached pool) do the same, as a smaller comparison so as not to strain the machine. Run with -Xmx1g.
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q94Virtual {
public static void main(String[] args) throws Exception {
Thread v = Thread.ofVirtual().name("order-7").start(() ->
System.out.println("inside: " + Thread.currentThread()));
v.join();
System.out.println("isVirtual=" + v.isVirtual() + ", isDaemon=" + v.isDaemon() + ", priority=" + v.getPriority());
Thread p = Thread.ofPlatform().name("plat-1").start(() -> { });
p.join();
System.out.println("platform isVirtual=" + p.isVirtual());
int n = 100_000;
AtomicInteger done = new AtomicInteger();
long t0 = System.nanoTime();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < n; i++) ex.submit(() -> { Thread.sleep(500); return done.incrementAndGet(); });
}
System.out.println(n + " virtual threads each sleeping 500 ms: " + (System.nanoTime() - t0) / 1_000_000 + " ms total, done=" + done);
int m = 2_000;
done.set(0);
t0 = System.nanoTime();
try (ExecutorService ex = Executors.newCachedThreadPool()) {
for (int i = 0; i < m; i++) ex.submit(() -> { Thread.sleep(500); return done.incrementAndGet(); });
}
System.out.println(m + " platform threads each sleeping 500 ms: " + (System.nanoTime() - t0) / 1_000_000 + " ms total, done=" + done);
}
}Make the invisible visible: Run it.
inside: VirtualThread[#26,order-7]/runnable@ForkJoinPool-1-worker-1
isVirtual=true, isDaemon=true, priority=5
platform isVirtual=false
100000 virtual threads each sleeping 500 ms: 1411 ms total, done=100000
2000 platform threads each sleeping 500 ms: 2350 ms total, done=2000What you see: The virtual thread prints as VirtualThread[#26,order-7]/runnable@ForkJoinPool-1-worker-1: an id, a name, and the carrier it was mounted on. It is a daemon with priority 5. 100,000 virtual threads that each slept 500 ms finished in 1.4 seconds total. Only 2,000 platform threads took 2.35 seconds.
Why: All 100,000 virtual threads were asleep at the same time, unmounted, while a handful of carriers ran the few that were awake. The platform threads each held a real OS thread. These are timings from one run on this machine, and your numbers will differ.
Platform thread
An OS thread. Large stack, a few thousand at most.
Thread t = Thread.ofPlatform()
.name("worker-1")
.start(() -> callPartner());
// 1 MB stack reserved, OS schedulesVirtual thread
A JVM object on a few carriers. Millions possible.
Thread t = Thread.ofVirtual()
.name("order-7")
.start(() -> callPartner());
// small heap stack, JVM schedulesThe shift: The code is nearly identical, but the virtual thread costs memory for its stack frames and no operating-system thread while it waits.
Land it I describe a virtual thread as a cheap JVM-scheduled thread that unmounts from its carrier when it blocks, so I can write blocking code and still hold many thousands of waits.
- "How many carrier threads are there, and can I change it?"
-
By default the number of carriers equals the number of cores, so 12 here. They are threads of a dedicated
ForkJoinPool, separate from the common pool used by parallel streams.You can tune it with system properties:
jdk.virtualThreadScheduler.parallelism(the number of carriers) andjdk.virtualThreadScheduler.maxPoolSize(the limit the pool may grow to when carriers are blocked in pinned or native calls). The pinning demo in Q96 sets both to 1 to make the effect obvious.Normally you leave them alone. Because virtual threads give up the carrier whenever they block, a few carriers can run many threads. More carriers than cores helps only if carriers are being held by pinned work.
The carriers are an implementation detail you should rarely name in code.
- "Why not pool virtual threads?"
-
A pool exists to reuse something expensive. A virtual thread is cheap to create (microseconds, a few hundred bytes to start), so there is nothing worth saving. Pooling them also brings back the limit you wanted to escape: a pool of 200 virtual threads handles 200 at a time, which is the problem Q95 starts from.
The rule is one virtual thread per task, created when needed and left to end.
Executors.newVirtualThreadPerTaskExecutor()does this, and it is still anExecutorService, so it works withsubmit,invokeAlland try-with-resources.If you need to limit concurrency, use a
Semaphorearound the scarce resource (Q97), not a smaller pool. - "How does a virtual thread show up in a thread dump?"
-
The classic
jstackdoes not list them, because there may be millions and they are not OS threads. You see only the carriers.The way to see them is
jcmd <pid> Thread.dump_to_file -format=json dump.json, which writes all threads including virtual ones, grouped by the thread containers (executors) that own them, with names and stacks.That is a reason to name virtual threads (Q79). A dump with 5,000 threads named
order-1234is readable. Five thousand unnamed ones are a wall of text.The JDK Flight Recorder also has events for virtual-thread start, end and pinning.
- "What stays the same from a programmer's point of view?"
-
Almost everything. A virtual thread is a
java.lang.Thread. You callstart,join,interruptandgetStateas usual. Blocking code looks the same, and an exception stack trace reads naturally from the task down.synchronized,ReentrantLock,BlockingQueueand the rest ofjava.util.concurrentwork.ThreadLocalworks, but with millions of threads each holding a large cached object, memory grows (E3 Q219).The things to unlearn are habits from the platform-thread era: sizing pools to limit threads, avoiding blocking calls, and moving everything into callbacks. For I/O-heavy services the old simple style returns.
Q95 · Scenario. "10,000 concurrent HTTP calls: a fixed pool of 200 versus virtual threads — what happens?"
Reveal answer
Strong answer With a fixed pool of 200, only 200 calls run at any moment. The other 9,800 wait in the queue for a free worker. If each call waits about 200 ms on the network, the 10,000 calls need 10,000 / 200 = 50 rounds of 200 ms, about 10 seconds, even though the threads are doing nothing but waiting. The last request waits nearly 10 seconds in the queue, and p99 latency explodes.
With a virtual-thread-per-task executor, all 10,000 calls start immediately, each on its own virtual thread. All 10,000 are blocked in the network at the same time, unmounted, so a few carrier threads suffice. The whole batch takes a little over 200 ms. Throughput is bounded by the network and the remote service, not by your thread count.
That is Little's law in action: concurrent requests in flight equal arrival rate times time spent per request. With 200 ms calls and a pool of 200, the pool can complete at most 1,000 calls per second. Virtual threads remove that ceiling.
The catch: removing your own limit exposes the next one. 10,000 simultaneous calls may overwhelm the remote service, your HTTP client's connection pool, or the database. The pool of 200 was accidentally protecting them. So when you move to virtual threads, add the limit back on purpose, with a Semaphore around the scarce resource (Q97, and the primer's Semaphore limit).
Also check your HTTP client's own limits. The JDK HttpClient has no per-host cap by default, but connection pools in other clients may.
The primer shows this as Virtual thread per task. E3 Q216 covers a team that kept the pool of 200 "to be safe", and Q217 a JDBC service that got slower.
Picture it 10,000 calls of 200 ms, with each executor.
The setup: The "call" is Thread.sleep(200), standing in for a network wait. The same 10,000 tasks run once through newFixedThreadPool(200) and once through newVirtualThreadPerTaskExecutor().
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Q95Gateway {
static final int CALLS = 10_000;
static long run(ExecutorService ex) throws Exception {
AtomicInteger done = new AtomicInteger();
long t0 = System.nanoTime();
try (ex) { for (int i = 0; i < CALLS; i++) ex.submit(() -> { Thread.sleep(200); return done.incrementAndGet(); }); }
if (done.get() != CALLS) throw new IllegalStateException();
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
System.out.println("fixed pool of 200: " + run(Executors.newFixedThreadPool(200)) + " ms for 10,000 calls of 200 ms");
System.out.println("virtual thread per task: " + run(Executors.newVirtualThreadPerTaskExecutor()) + " ms for 10,000 calls of 200 ms");
}
}Make the invisible visible: Run it.
fixed pool of 200: 10031 ms for 10,000 calls of 200 ms
virtual thread per task: 247 ms for 10,000 calls of 200 msWhat you see: The fixed pool took 10,031 ms, the 50 rounds of 200 ms. The virtual-thread executor took 247 ms.
Why: The pool's size was the bottleneck, not the work. Both runs did the same 10,000 waits, but the pool could only overlap 200 of them. Numbers are from one run on this machine.
Fixed pool of 200
Queue wait dominates. 50 rounds of 200 ms.
try (var ex =
Executors.newFixedThreadPool(200)) {
for (int i = 0; i < 10_000; i++)
ex.submit(() -> callPartner());
} // about 10 secondsVirtual thread per task
All calls wait at the same time.
try (var ex = Executors
.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++)
ex.submit(() -> callPartner());
} // a little over 200 msThe shift: A pool size that was a safety limit becomes a throughput ceiling, and virtual threads lift it, so you must add the safety limit back deliberately.
Land it I move blocking I/O to a virtual thread per task so the thread count stops limiting throughput, and I add a Semaphore to protect whatever is now the bottleneck.
- "Would a bigger fixed pool, say 10,000 threads, give the same result?"
-
For this demo, almost, but at a heavy cost. 10,000 platform threads would each reserve a stack, take time to create (Q71 showed about 0.13 ms each, over a second for 10,000), and strain the operating system's limits. It may fail on a container with a low process limit.
The cost is paid per thread, and in a service with thousands of requests per second the pool must stay that large permanently. Virtual threads pay almost nothing for a waiting task, so you can have as many as you have concurrent requests.
The programming model matters too. A pool of 10,000 needs tuning, monitoring and a hard limit anyway. A virtual thread per task has no size to tune.
So the answer is "it works in the demo, and it does not scale or tune well". That is the whole case for virtual threads.
- "How do I limit concurrency now that there is no pool?"
-
Put a
Semaphorearound the resource that needs protecting, not around the thread.SemaphoreLimit.javaruns offline// illustrative Semaphore partner = new Semaphore(50); // partner allows 50 String call() throws InterruptedException { partner.acquire(); try { return http.send(request).body(); } finally { partner.release(); } }Virtual threads waiting on
acquire()are unmounted and cost almost nothing, so thousands can queue there safely. The permit count is the real limit: what the downstream can take.Size it from the downstream's capacity (a database pool of 20 means a semaphore of about 20), not from your CPU count. Q80 showed the same device holding 200 tasks to 20 at a time.
- "What did the HTTP client do with a pool of 200 threads and blocking calls?"
-
Each of the 200 threads called the blocking
HttpClient.sendor an older client, and sat in a socket read for about 200 ms. During that time the thread did no useful work. The CPU graph looked idle while the latency graph climbed.That is the signature of a thread-bound service: low CPU, rising latency, and a thread dump with the pool threads all in the same socket wait. It tells you that more concurrency, not more CPU, is the missing resource.
The classic remedies were a bigger pool (memory heavy), an async client with callbacks (complex code), or reactive streams (a different programming model). Virtual threads give the same capacity with the simple blocking style.
- "When would the fixed pool still be the right answer?"
-
When the work is CPU-bound, when you need a hard cap on concurrency without a semaphore, or when you are on Java 17 or older.
For CPU-bound work, a pool near the core count is correct. Extra threads of any kind just compete for the same cores (Q97 shows no speed-up from virtual threads). For a cap, a fixed pool is a one-line limit, but only for the work it runs.
On old Java, 200 threads and a queue is the practical choice. Some teams also keep a pool where they use
ThreadLocalcaches that assume a bounded thread count.For blocking I/O on Java 21 or later, virtual threads are the default I would start with.
Q96. "What was pinning, and what changed in Java 24?"
Reveal answer
Strong answer Pinning is when a virtual thread cannot unmount from its carrier while it blocks. Normally a blocked virtual thread steps off the carrier so the carrier can run other work. A pinned one stays stuck to the carrier, so a blocking call holds a real OS thread, which is the cost virtual threads were meant to remove.
In Java 21 through 23, the main cause was synchronized. If a virtual thread blocked while inside a synchronized block or method (a sleep, a socket read, waiting for another monitor, or Object.wait()), it stayed pinned. A service with many virtual threads blocking inside synchronized code could use up all its carriers (one per core by default), and then everything stalled. The other pinning case is a native method or foreign function frame on the stack, which still pins.
Java 24 (JEP 491) removed the synchronized case. The JVM can now unmount a virtual thread that blocks inside a monitor. A virtual thread blocked on Object.wait() or waiting to enter a monitor no longer holds its carrier.
What still pins in Java 24 and later: a blocking call while a native frame or a foreign call is on the stack, and class initialisation (static initialisers running). Those are rare in application code.
What to do on each version. On Java 21, 22 or 23: prefer ReentrantLock over synchronized around blocking calls, and diagnose with -Djdk.tracePinnedThreads=full or the JFR event jdk.VirtualThreadPinned. On 24 and later you can stop rewriting synchronized code for this reason. Upgrading is the fix.
The demo below shows the effect on one carrier. E3 Q217 describes a JDBC service that slowed down on virtual threads, and E2 Modern Concurrency has the internals.
Picture it Four virtual threads, one carrier, each sleeping 200 ms inside synchronized on its own lock.
The setup: I set the scheduler to one carrier thread with these flags:
-Djdk.virtualThreadScheduler.parallelism=1 \
-Djdk.virtualThreadScheduler.maxPoolSize=1Each task locks its own object, so there is no contention between tasks, and sleeps 200 ms inside the lock. A second round sleeps without any lock. I run the same file on JDK 21 and JDK 25.
import java.util.concurrent.*;
public class Q96Pinning {
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 4; i++) {
ex.submit(() -> {
Object mine = new Object(); // each task has its OWN lock: no contention
synchronized (mine) { // sleep INSIDE synchronized
try { Thread.sleep(200); } catch (InterruptedException e) { }
}
});
}
}
System.out.println("4 virtual threads, 1 carrier, sleep inside synchronized: " + (System.nanoTime() - t0) / 1_000_000 + " ms");
t0 = System.nanoTime();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 4; i++) {
ex.submit(() -> { try { Thread.sleep(200); } catch (InterruptedException e) { } });
}
}
System.out.println("4 virtual threads, 1 carrier, plain sleep (no lock): " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
}Make the invisible visible: Run it on each JDK, with one carrier.
$ /usr/lib/jvm/java-21-openjdk-amd64/bin/java -Djdk.virtualThreadScheduler.parallelism=1 \
-Djdk.virtualThreadScheduler.maxPoolSize=1 Q96Pinning.java
4 virtual threads, 1 carrier, sleep inside synchronized: 811 ms
4 virtual threads, 1 carrier, plain sleep (no lock): 201 ms
$ java -Djdk.virtualThreadScheduler.parallelism=1 -Djdk.virtualThreadScheduler.maxPoolSize=1 Q96Pinning.java
4 virtual threads, 1 carrier, sleep inside synchronized: 211 ms
4 virtual threads, 1 carrier, plain sleep (no lock): 201 msWhat you see: On JDK 21 the sleeping-inside-synchronized version took 811 ms: the four threads took turns on the single carrier, 4 times 200 ms. On JDK 25 it took 211 ms, the same as the lock-free version, because each sleeper unmounted and the carrier served all four.
Make the invisible visible: JDK 21 can also print the pinned stack with -Djdk.tracePinnedThreads=short.
VirtualThread[#23]/runnable@ForkJoinPool-1-worker-1 reason:MONITOR
Q96Pinning.lambda$main$0(Q96Pinning.java:11) <== monitors:1
4 virtual threads, 1 carrier, sleep inside synchronized: 809 ms
4 virtual threads, 1 carrier, plain sleep (no lock): 200 msWhy: On JDK 21 the trace names the pinned frame (lambda$main$0, with monitors:1: one monitor held). On JDK 25 the same flag printed nothing during my run, because the property was removed in JDK 24 together with JEP 491, and nothing pins on synchronized there anyway. On Java 24 and later use JFR's jdk.VirtualThreadPinned event for the cases that still pin. I printed only the first lines of the JDK 21 trace.
Java 21 to 23
A sleep inside synchronized holds the carrier.
synchronized (lock) {
Thread.sleep(200); // PINNED
}
// 4 tasks, 1 carrier: 800 msJava 24 and later
The same code unmounts and frees the carrier.
synchronized (lock) {
Thread.sleep(200); // unmounts
}
// 4 tasks, 1 carrier: about 200 msThe shift: The language did not change. The JVM learned to take a virtual thread off its carrier even inside a monitor.
Land it I explain pinning as a virtual thread stuck to its carrier while blocked, mostly through synchronized before Java 24, and I say the cure was JEP 491 plus ReentrantLock on older versions.
- "How did you diagnose pinning on Java 21?"
-
Two tools. The system property
-Djdk.tracePinnedThreads=full(orshort) prints a stack trace whenever a virtual thread blocks while pinned, with the frames that hold monitors marked. That points at the exactsynchronizedblock.The JDK Flight Recorder event
jdk.VirtualThreadPinnedrecords the same thing with its duration, and is cheaper to leave on in production. A threshold of 20 ms is the default.The symptoms to look for: throughput that plateaus at roughly your core count despite many virtual threads, a CPU that is low, and carrier threads all blocked in socket or sleep calls.
The fixes on Java 21: replace the
synchronizedaround blocking calls withReentrantLock, shorten the locked region so it does not contain the I/O, or upgrade to 24 or later. Old libraries that usesynchronizedaround I/O, such as some JDBC drivers, were common offenders. - "Does Java 24 remove all pinning?"
-
No. It removes the monitor case, which was by far the most common. Two cases remain: blocking while a native method or foreign function is on the stack (the JVM cannot move a native frame off the carrier), and blocking inside a class initialiser, which holds an internal class-initialisation lock.
Both are uncommon in application code. A JNI call that calls back into Java and then blocks is the typical native case.
When pinning happens, the virtual thread still works. It blocks its carrier for the wait. Only throughput suffers, and only if many threads do it at once.
The JFR event
jdk.VirtualThreadPinnedstill reports these. I treat it as a monitoring signal, not as an error. - "Should I rewrite synchronized to ReentrantLock because of pinning?"
-
On Java 24 or later, no. The reason is gone, and
synchronizedis simpler and cannot leak a lock.On Java 21, 22 and 23, only where it matters: a
synchronizedblock that contains a blocking call (I/O, sleep, waiting on another lock) and runs often under many virtual threads. Asynchronizedblock around a few field updates is harmless, because it is short and never blocks.Measure first with the trace flag or JFR, then fix the hot spots. A blanket rewrite adds risk (a forgotten
unlock) for little gain.Often the better fix is to move the blocking call out of the lock: read what you need under the lock, release it, then do the I/O.
- "What did the demo prove, and what did it not?"
-
It proved the effect in isolation. With one carrier and four tasks that sleep inside
synchronizedon separate locks, JDK 21 took 811 ms and JDK 25 took 211 ms. Because each task used its own lock, there was no lock contention to hide the difference.It did not prove how much pinning costs in a real service. There, the effect depends on how long blocking calls last, how many carriers you have, and how many threads block inside monitors at once. With 12 carriers, a few pinned threads change little.
The first version of my demo used one shared lock and showed 800 ms on both JDKs, because the tasks had to take turns for the lock anyway. That mistake is worth remembering: a pinning benchmark must remove other sources of serialisation.
Q97. "When should you not use virtual threads?"
Reveal answer
Strong answer Virtual threads help when a task spends most of its time waiting. They do not help, and can hurt, in these cases.
- CPU-bound work: a virtual thread still needs a core to compute. 12 cores run 12 calculations at a time whether you have 12 threads or 12,000. The demo shows no speed-up.
- Pooling them: a pool of virtual threads reintroduces the limit and the queue you wanted to remove. Create one per task. Limit concurrency with a
Semaphore. - Heavy ThreadLocal caches: code that stores a large per-thread buffer (an 8 KB parser, a database session) in a
ThreadLocalmultiplies it by the number of virtual threads. Millions of threads mean gigabytes. Use scoped values or share the object. - Pinning on old Java: before 24, blocking inside
synchronizedheld the carrier (Q96). - Scarce downstream resources: a database pool of 20 cannot serve 10,000 concurrent queries. Without a limit, virtual threads queue on the connection pool, and timeouts and thundering herds follow (E3 Q217).
- Code relying on thread identity or priority: virtual threads ignore priorities and are always daemon. Code that uses thread count as a limit or keeps per-thread state changes meaning.
A short test: if you could not make the task faster by buying more cores, or if it holds a lock or a limited resource for most of its time, think twice.
They are also not a reason to avoid other tools. A parallel stream is still right for CPU work on a collection, and an executor sized to the cores is right for CPU tasks.
The primer's decision tree in Virtual threads summarises this. E3 Q218 and Q219 cover when they do not help and the ThreadLocal memory problem.
Picture it 48 pure-CPU tasks on three executors.
The setup: Each task runs a tight arithmetic loop of 60 million steps (no waiting). The 48 tasks run on a fixed pool of 12 platform threads (the core count), on virtual threads, and on a pool of 200 platform threads. A warm-up round runs first.
import java.util.concurrent.*;
public class Q97CpuBound {
static long burn(int seed) { long x = seed; for (int i = 0; i < 60_000_000; i++) x = x * 31 + i; return x; }
static long timeIt(ExecutorService ex, int tasks) throws Exception {
long t0 = System.nanoTime();
try (ex) { for (int i = 0; i < tasks; i++) { int s = i; ex.submit(() -> burn(s)); } }
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
timeIt(Executors.newFixedThreadPool(cores), cores); // warm-up
System.out.println("cores = " + cores + ", tasks = " + cores * 4 + " (each pure CPU work)");
System.out.println("fixed pool of " + cores + " platform threads: " + timeIt(Executors.newFixedThreadPool(cores), cores * 4) + " ms");
System.out.println("virtual thread per task: " + timeIt(Executors.newVirtualThreadPerTaskExecutor(), cores * 4) + " ms");
System.out.println("fixed pool of 200 platform: " + timeIt(Executors.newFixedThreadPool(200), cores * 4) + " ms");
}
}Make the invisible visible: Run it.
cores = 12, tasks = 48 (each pure CPU work)
fixed pool of 12 platform threads: 289 ms
virtual thread per task: 299 ms
fixed pool of 200 platform: 273 msWhat you see: All three took about the same time: 289 ms, 299 ms and 273 ms. Virtual threads did not make the computation faster.
Why: The limit was 12 cores, not thread count. Every executor kept all 12 cores busy, and extra threads only waited their turn. The small differences are noise from one run.
CPU-bound task
No waiting, so unmounting never happens.
ex.submit(() -> {
long x = 0;
for (int i = 0; i < 60_000_000; i++)
x = x * 31 + i;
return x; // never blocks
});I/O-bound task
Mostly waiting, so unmounting frees the carrier.
ex.submit(() -> {
var resp = http.send(req, ofString());
return resp.body(); // blocks: unmounts
});The shift: Virtual threads multiply how many things can wait, not how much can be computed.
Land it I keep virtual threads for waiting work and use a core-sized pool or a parallel stream for computation, and I never pool virtual threads.
- "Why do millions of ThreadLocals become a problem?"
-
A
ThreadLocalstores one value per thread. With 200 pool threads, a 1 MB cached buffer per thread costs 200 MB. With 100,000 virtual threads, each holding its own, it costs 100 GB, and the heap runs out (E3 Q219 shows the heap dump).The pattern was designed for a small, fixed set of long-lived threads, where per-thread caching was a cheap form of object reuse. Virtual threads are short-lived and numerous, so per-thread caches stop paying off.
Fixes: share thread-safe objects (a
DateTimeFormatteris immutable), use a small pool of reusable objects, or useScopedValuefor context data (Q98).Also check libraries. Some old libraries keep large per-thread caches without telling you. A heap dump with a big retained size under
ThreadLocalMappoints at them. - "Should CPU-bound work ever run on a virtual thread?"
-
It can, with care. A virtual thread that computes for a long time without blocking keeps its carrier, and other virtual threads cannot use that carrier. With 12 carriers and 12 CPU-heavy virtual threads, the carriers are all busy, and short I/O tasks wait.
The JVM does not time-slice virtual threads (they are not preempted), so a long compute loop starves others sharing the carriers.
Mixed workloads should separate the two: CPU-bound tasks on a fixed pool sized near the core count, I/O tasks on virtual threads. A request thread, virtual, calls
cpuPool.submit(...).get()for the heavy step, and waiting for that is cheap.In the demo all three executors were equal because the work was equal. The risk appears when the two kinds share carriers.
- "Do virtual threads make an existing service faster?"
-
Only if the service is limited by its thread count. The sign is low CPU with high latency and a thread dump full of threads waiting on I/O. Then virtual threads raise the number of requests in flight, and throughput rises until the next limit appears (a connection pool, a remote service).
If the service is limited by CPU, by a database, or by a lock, nothing improves. Latency of a single request does not change either, because one call still takes its 200 ms.
So the benefit is capacity under many waits, not speed per request. Measure before and after with a load test, and look at the whole chain: more concurrency often moves the bottleneck to the database.
The usual surprise is that the database gets slower, since 5,000 requests now reach a pool of 20 connections. A
Semaphoreor a bounded connection pool decides what happens next (Q95). - "What does one virtual thread cost in memory?"
-
A virtual thread starts with a stack of a few hundred bytes to about a kilobyte, kept as a heap object, and the stack grows and shrinks with the call depth. A thread that is blocked at a depth of 30 frames may hold a few kilobytes.
That is roughly a thousand times less than the 1 MB of address space reserved for a platform thread, which is why 100,000 of them ran in the Q94 demo with a 1 GB heap.
The cost grows with what the thread holds: deep call stacks, large local objects and
ThreadLocalvalues. A million threads each holding 10 KB is 10 GB, so "cheap" still means "measure".Heap size and garbage collection settings matter more than with platform threads, because the stacks are on the heap. I watch heap use and GC pause time during the first load test of any virtual-thread service.
Q98. "Scoped values versus ThreadLocal with virtual threads."
Reveal answer
Strong answer Both carry a piece of context (a request id, the current user, a trace id) down through many method calls without passing it as a parameter. They differ in how long the value lives, who may change it, and what it costs.
A ThreadLocal is a variable with one copy per thread. You call set to store and get to read. The value lives until you call remove or the thread dies. It is mutable: any code on the thread can change it. A pooled thread that forgets remove leaks one request's value into the next. And each thread holds its own copy, so a million virtual threads can hold a million copies.
A ScopedValue (final in Java 25) is bound for the duration of one block: ScopedValue.where(REQUEST_ID, "req-42").run(() -> handle()). Inside the block and the calls it makes, REQUEST_ID.get() returns that value. When the block ends, the binding disappears, so it cannot leak. It is immutable inside the block. You can rebind it in a nested block for a smaller scope (the demo shows req-42-retry), and the outer value returns afterwards.
Scoped values cost less. The binding is shared with child tasks, not copied per thread, and lookup is fast. They are designed for virtual threads and structured concurrency: subtasks forked in a StructuredTaskScope inherit the binding automatically (the Q99 demo shows it).
What a scoped value is not: a mutable, per-thread cache. You cannot set it, and it is not inherited by plain threads you start yourself. If you need mutable per-thread state (rare), ThreadLocal still exists and works on virtual threads, but with the memory caution of Q97.
Migration advice: for read-only context (request id, user, tenant, locale), move to scoped values. Keep ThreadLocal for old libraries that need it. Frameworks such as logging MDC and security contexts will take time to adopt them.
The primer covers it in Virtual threads, and E2 Modern Concurrency has the internals. E3 Q219 shows the ThreadLocal memory blow-up.
Picture it A request id passed with a scoped value, and the ThreadLocal leak it avoids.
The setup: A ScopedValue and a ThreadLocal. The scoped value is bound in run, rebound in a nested block, and read after the block. A new virtual thread reads both. Then a one-thread pool simulates request A leaving a ThreadLocal value that request B sees, while a scoped binding is gone after the block.
import java.util.concurrent.*;
public class Q98Scoped {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static final ThreadLocal<String> TL = new ThreadLocal<>();
static void deep(String label) {
System.out.println(label + ": scoped=" + (REQUEST_ID.isBound() ? REQUEST_ID.get() : "<unbound>") + " threadLocal=" + TL.get());
}
public static void main(String[] args) throws Exception {
ScopedValue.where(REQUEST_ID, "req-42").run(() -> {
deep("inside run()");
ScopedValue.where(REQUEST_ID, "req-42-retry").run(() -> deep("nested rebinding"));
deep("after nested scope");
});
deep("outside the scope");
TL.set("tl-42");
Thread plain = Thread.ofVirtual().start(() -> deep("new virtual thread"));
plain.join();
// ThreadLocal leak: it lives as long as the thread, unless somebody removes it
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
pool.submit(() -> TL.set("left behind by request A")).get();
pool.submit(() -> System.out.println("request B on the same pool thread sees: " + TL.get())).get();
}
// ScopedValue does not leak
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
pool.submit(() -> ScopedValue.where(REQUEST_ID, "req-A").run(() -> { })).get();
pool.submit(() -> System.out.println("request B sees scoped bound? " + REQUEST_ID.isBound())).get();
}
}
}Make the invisible visible: Run it.
inside run(): scoped=req-42 threadLocal=null
nested rebinding: scoped=req-42-retry threadLocal=null
after nested scope: scoped=req-42 threadLocal=null
outside the scope: scoped=<unbound> threadLocal=null
new virtual thread: scoped=<unbound> threadLocal=null
request B on the same pool thread sees: left behind by request A
request B sees scoped bound? falseWhat you see: Inside the block the scoped id was req-42, in the nested block req-42-retry, and after it back to req-42. Outside the scope it was unbound. A new virtual thread saw neither value. On the pool, request B saw the value left behind by request A in the ThreadLocal, but the scoped value was unbound again.
Why: The scoped value's lifetime is the block, so the leak cannot happen. The ThreadLocal lived with the pooled thread, and nobody called remove.
ThreadLocal
Set, read, remember to remove. Mutable and per thread.
static ThreadLocal<String> ID =
new ThreadLocal<>();
ID.set("req-42");
try { handle(); }
finally { ID.remove(); }ScopedValue
Bound for one block. Immutable and cleaned up for you.
static final ScopedValue<String> ID =
ScopedValue.newInstance();
ScopedValue.where(ID, "req-42")
.run(() -> handle());The shift: A scoped value ties the context to a block of code, so the cleanup that ThreadLocal asks you to remember happens by construction.
Land it I use scoped values for read-only request context, because the binding ends with the block and is shared cheaply with forked tasks, while ThreadLocal leaks and multiplies with virtual threads.
- "Are scoped values available in Java 21?"
-
As a preview, not final. Scoped values were incubated in Java 20, previewed in 21 to 24, and became final in Java 25 (JEP 506). On 21, 22, 23 and 24 you need
--enable-preview(Q19 covers preview features).The API changed a little between previews. In the final version you bind and run with
ScopedValue.where(KEY, value).run(...)or.call(...), and read withKEY.get(),KEY.isBound()orKEY.orElse(...).For a library that must support Java 17 or 21 without preview flags,
ThreadLocalremains the only option, and you hide it behind a small interface that can switch later. - "How does the value reach forked subtasks?"
-
Through structured concurrency. When you open a
StructuredTaskScopeinside a scoped-value block and fork subtasks, each subtask sees the same bindings, with no copying. The demo in Q99 printssubtask sees req-42.That works because the scope guarantees the subtasks end before the block does, so the binding is still valid for their whole life. A plain
new Threadhas no such guarantee, and scoped values are not inherited by it.Compare
InheritableThreadLocal, which copies the value into each child thread when it is created. That copy costs memory per thread and cannot be updated afterwards. - "Can I change a scoped value inside the block?"
-
No. A scoped value is immutable within a binding. To "change" it, rebind it for a nested block with
ScopedValue.where(KEY, newValue).run(...), which is what the demo does with the retry id. When the nested block ends, the outer value is visible again.That rule is the point: code that reads the value cannot be surprised by a change from elsewhere on the same thread, which is a classic
ThreadLocalsource of bugs.If you really need a mutable holder, bind a scoped value to a mutable object (an
AtomicReferenceor a small context class). It is possible, and it brings back the thread-safety questions, so keep the data immutable if you can. - "What about MDC logging and security contexts that use ThreadLocal?"
-
They still do, and they work on virtual threads, since
ThreadLocalis supported. The per-thread memory cost is small for a few strings, and it matters only for large objects.The real problem is propagation. When work hops to another thread (
supplyAsync, a forked task), theThreadLocalis not copied, so the log line loses its request id (Q89). Frameworks solve it with executor wrappers that capture and restore the context.As libraries adopt scoped values, the propagation will come with structured concurrency. Until then I wrap executors with a context-propagating decorator and set the MDC at the start of each task.
Q99. "What is structured concurrency, and why is it still a preview in Java 25–27?"
Reveal answer
Strong answer Structured concurrency is a rule for concurrent code: when a task splits into subtasks, the subtasks must all finish before the code that started them moves on. The lifetime of a thread is tied to a block of code, like a local variable, instead of floating free.
Plain threads and executors break that rule. A task that submits three subtasks and fails halfway leaves the other two running, unseen, perhaps for minutes. Errors do not flow back to the parent, cancellation does not reach the children, and a thread dump cannot tell you which request a thread belongs to.
In Java, StructuredTaskScope (using a try-with-resources block) gives the rule shape. You open a scope, fork subtasks (each on a virtual thread), call join(), and leave the block. If one subtask fails, the scope can cancel the siblings and join() throws. If the parent is cancelled, so are the children. The scope also passes ScopedValue bindings down to them.
The code reads like plain sequential code, with normal try/catch and clean stack traces, and it cannot leak a thread past its block. It works well with the checkout example: three calls, all or nothing, fail fast.
It is still a preview API: incubating from Java 19, preview from 21 and on to Java 27, and it shows up again in each release (5th preview in 25, 6th in 26, 7th in 27). The reason is that the API has been redesigned between previews. In Java 25 you call StructuredTaskScope.open() with a Joiner that sets the policy (all succeed, first success, and so on), instead of the earlier subclasses with ShutdownOnFailure. The designers are collecting feedback before they fix the shape for a decade or more.
Because it is a preview, you must compile and run with --enable-preview, and class files are tied to that exact Java version, so you should not ship it in a library for others. Use it for experiments, and use CompletableFuture or executors in production code.
The primer shows the run in Virtual threads, and E3 Q220 explains it in plain words.
Picture it All three subtasks succeed, then one fails fast, then a scoped value flows in, all on JDK 25 with preview enabled.
The setup: StructuredTaskScope.open() forks menu, price and ETA. A second scope forks a 2-second task and a task that fails after 100 ms. A third scope reads a ScopedValue inside a subtask. First I try to run it with no flag.
import java.util.concurrent.*;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Q99Structured {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static void sleep(int ms) throws InterruptedException { Thread.sleep(ms); }
static String menu() throws Exception { sleep(300); return "menu"; }
static int price() throws Exception { sleep(250); return 499; }
static String eta(boolean fail) throws Exception {
try { sleep(350); if (fail) throw new IllegalStateException("rider service down"); return "22 min"; }
catch (InterruptedException e) { System.out.println(" eta/menu/price subtask was CANCELLED (interrupted)"); throw e; }
}
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
try (var scope = StructuredTaskScope.open()) {
Subtask<String> m = scope.fork(() -> menu());
Subtask<Integer> p = scope.fork(() -> price());
Subtask<String> e = scope.fork(() -> eta(false));
scope.join();
System.out.println("all ok: " + m.get() + ", " + p.get() + ", " + e.get() + " in " + (System.nanoTime() - t0) / 1_000_000 + " ms");
}
System.out.println("--- one fails: the others are cancelled and the error comes out of join()");
t0 = System.nanoTime();
try (var scope = StructuredTaskScope.open()) {
scope.fork(() -> { sleep(2000); return "slow menu"; });
scope.fork(() -> { sleep(100); throw new IllegalStateException("price service down"); });
scope.join();
} catch (Exception ex) {
System.out.println("join() threw " + ex.getClass().getSimpleName() + " with cause " + ex.getCause() + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms (not 2000)");
}
System.out.println("--- scoped values flow into forked subtasks");
ScopedValue.where(REQUEST_ID, "req-42").run(() -> {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> s = scope.fork(() -> "subtask sees " + REQUEST_ID.get());
scope.join();
System.out.println(s.get());
} catch (Exception ex) { }
});
}
}Make the invisible visible: Without the flag, then with it.
Q99Structured.java:2: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope.Subtask;
^
(use --enable-preview to enable preview APIs)
Q99Structured.java:2: error: Subtask is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope.Subtask;
^
(use --enable-preview to enable preview APIs)all ok: menu, 499, 22 min in 361 ms
--- one fails: the others are cancelled and the error comes out of join()
join() threw FailedException with cause java.lang.IllegalStateException: price service down after 104 ms (not 2000)
--- scoped values flow into forked subtasks
subtask sees req-42What you see: Without the flag the compiler refused: "StructuredTaskScope is a preview API and is disabled by default". With the flag, the three calls finished in 361 ms. In the failing scope, join() threw FailedException with the real cause after 104 ms, not 2,000: the slow sibling was cancelled. The subtask saw the scoped value req-42.
Why: The scope owned its subtasks. A failure in one cancelled the rest, and leaving the block was impossible until all subtasks had ended. The API shape (open(), fork, join) is that of JDK 25 and may change in later previews.
Unstructured
Subtasks outlive their parent. Errors and cancel are manual.
var f1 = pool.submit(this::menu);
var f2 = pool.submit(this::price);
f1.get(); // f2 keeps running
// if f1 fails, who cancels f2?Structured
Subtasks end inside the block. A failure cancels siblings.
try (var scope =
StructuredTaskScope.open()) {
var m = scope.fork(() -> menu());
var p = scope.fork(() -> price());
scope.join(); // all done or failed
}The shift: The block becomes the boundary of the work, so no task can outlive the code that asked for it.
Land it I describe structured concurrency as tying subtasks to a block so errors and cancellation flow, and I say it is still preview because the API keeps being redesigned, so I do not ship it yet.
- "What does preview mean for my build and deploy?"
-
A preview feature is complete and specified, but not permanent. Using one requires
--enable-previewat compile and at run time (and--source Nfor the source launcher). The class files you produce are marked with the exact Java version, and the JVM refuses to run them on any other version.So a preview build is locked to one JDK feature release: a jar that uses preview on 25 will not load on 26. That makes it unsuitable for libraries and a burden for services that upgrade often.
Preview APIs can also change or disappear. String templates were previewed in 21 and 22 and then withdrawn. For learning, prototyping and internal tools it is fine. For production code, wait for final.
Q19 covers previews in general.
- "How does a failing subtask cancel the others?"
-
The scope's Joiner decides the policy. With the default policy of
open()in Java 25,join()waits for all subtasks to succeed, and if any fails, the scope cancels the rest by interrupting their virtual threads andjoin()throws aFailedExceptionwith the first failure as its cause.Other joiners give other policies:
anySuccessfulResultOrThrow()returns the first success and cancels the rest (likeinvokeAny), andawaitAll()waits for everything and never cancels. The API for joiners is exactly the part that changed between previews, so check the Javadoc for your release.The cancellation is interruption, so the subtasks must respond to it, as in Q73. The demo's 2-second task slept, so it woke at once.
- "What would I use today for the same all-or-nothing fan-out?"
-
Three options, none preview.
CompletableFuture.allOfwith anorTimeoutand a handler (Q91). Works on Java 8 or later, and cancellation of siblings is manual.invokeAllon a virtual-thread executor, with a timeout. Simple, and failures show onget().- An
ExecutorServicewith explicit cancellation: on the first failure, callcancel(true)on the other futures yourself.
I use the first for composition with fallbacks and the second for plain batches. When structured concurrency is final, I expect to move the all-or-nothing cases to it, because the cancellation and error flow are the parts that are easy to get wrong by hand.
- "Why is it better than a CompletableFuture chain?"
-
For all-or-nothing work, the shape of the code is the benefit. Each step reads as ordinary statements in order. Errors surface as normal exceptions at
join(), and a stack trace shows the parent method. No subtask can outlive the block, and cancellation is automatic.A
CompletableFuturepipeline separates the description of the work from where it runs, so a failure is a stored value that you must remember to inspect (Q92). Stack traces show library internals.The
CompletableFuturestill has strengths: per-call fallbacks, combinators such asthenCombine, working on any Java 8+, and no preview flag. The new tool does not make it obsolete.In thread dumps, a scope also makes each thread's owner visible, because the dump format for virtual threads shows the thread container tree.
Q100 · Design. "Choose the concurrency tool — parallel stream, executor, CompletableFuture, virtual threads or structured concurrency — for five real workloads."
Reveal answer
The real test Whether you choose by what the work is waiting on, not by fashion: CPU on cores, many waits on virtual threads, composition with fallbacks on CompletableFuture, all-or-nothing fan-out on structured concurrency (when final).
Strong answer Start from one question: what is the work spending its time on? CPU, waiting, or coordinating other work? Then match the tool. Here are five QuickBite workloads.
| Workload | Tool | Why | Watch out for |
|---|---|---|---|
| 1. Nightly revenue report over 20 million order rows in memory | Parallel stream | CPU-bound, splittable source, no shared state | Use collect, never a shared map; measure against sequential |
| 2. Image resizing for 500 menu photos | Executor sized near the core count | CPU-bound tasks, each independent, with results needed | More threads than cores only adds switching |
| 3. Checkout: menu, price and ETA with fallbacks | CompletableFuture | Combines independent results, per-call fallback and timeout | Own executor; end with a handler |
| 4. Partner gateway: 5,000 concurrent blocking calls | Virtual threads, with a Semaphore | Mostly waiting; one thread per task is simplest | Limit the downstream; no pooling |
| 5. Dashboard that needs all three services or fails fast | Structured concurrency (preview; else invokeAll) | All-or-nothing with automatic cancellation | Preview: not for production yet |
Two supporting rules decide ties. Shared counters go in atomics (LongAdder under contention), and invariants over several fields go under a lock. Tools solve the running of work, and these solve the sharing of data.
Questions I ask before choosing: Is the work CPU or waiting? How many at once? Do results depend on each other? What should happen to siblings when one fails? Which Java version am I on? Where is the real limit: cores, a connection pool, a remote rate limit?
Then I measure. The demo below runs a small version of workloads 1 to 5 and prints the time of each.
The primer closes with this decision tree in Virtual threads. E3 Q184 gives sizing numbers, and Q216 to Q220 cover the virtual-thread and structured-concurrency judgement calls.
Picture it Five tiny workloads, each with the tool from the table, timed on one run.
The setup: Count primes below 3 million with a sequential and a parallel stream. Run the same count in 12 chunks on a fixed pool. Run 5,000 sleeping calls of 200 ms on virtual threads. Combine two async results with CompletableFuture. Run a scope where one subtask fails fast. It needs --enable-preview for the last one.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class Q100Workloads {
static void nap(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } }
static boolean prime(int n) { if (n < 2) return false; for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) return false; return true; }
static long ms(long t0) { return (System.nanoTime() - t0) / 1_000_000; }
public static void main(String[] args) throws Exception {
long t0 = System.nanoTime();
long a = IntStream.rangeClosed(1, 3_000_000).filter(Q100Workloads::prime).count();
long seq = ms(t0); t0 = System.nanoTime();
long b = IntStream.rangeClosed(1, 3_000_000).parallel().filter(Q100Workloads::prime).count();
System.out.println("1 CPU over a big collection : sequential " + seq + " ms, parallel stream " + ms(t0) + " ms (" + a + " = " + b + " primes)");
int cores = Runtime.getRuntime().availableProcessors();
t0 = System.nanoTime();
try (ExecutorService pool = Executors.newFixedThreadPool(cores)) {
List<Future<Long>> fs = new ArrayList<>();
for (int i = 0; i < cores; i++) { int lo = i * 250_000; fs.add(pool.submit(() -> IntStream.range(lo, lo + 250_000).filter(Q100Workloads::prime).count())); }
long s = 0; for (Future<Long> f : fs) s += f.get();
System.out.println("2 CPU tasks, own pool of " + cores + " : " + ms(t0) + " ms (" + s + " primes below 3,000,000)");
}
t0 = System.nanoTime();
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5_000; i++) vt.submit(() -> nap(200));
}
System.out.println("3 5,000 blocking calls of 200 ms, virtual threads: " + ms(t0) + " ms");
t0 = System.nanoTime();
CompletableFuture<String> r = CompletableFuture.supplyAsync(() -> { nap(300); return "menu"; })
.thenCombine(CompletableFuture.supplyAsync(() -> { nap(250); return "price"; }), (m, p) -> m + "+" + p);
r.join();
System.out.println("4 compose two async results (CompletableFuture): " + ms(t0) + " ms");
t0 = System.nanoTime();
try (var scope = StructuredTaskScope.open()) {
scope.fork(() -> { nap(3000); return "slow"; });
scope.fork(() -> { nap(100); throw new IllegalStateException("down"); });
scope.join();
} catch (Exception e) { System.out.println("5 all-or-nothing fan-out (structured): failed fast in " + ms(t0) + " ms, others cancelled"); }
}
}Make the invisible visible: Run it.
1 CPU over a big collection : sequential 1997 ms, parallel stream 525 ms (216816 = 216816 primes)
2 CPU tasks, own pool of 12 : 816 ms (216816 primes below 3,000,000)
3 5,000 blocking calls of 200 ms, virtual threads: 289 ms
4 compose two async results (CompletableFuture): 304 ms
5 all-or-nothing fan-out (structured): failed fast in 107 ms, others cancelledWhat you see: The parallel stream took 525 ms against 1,997 ms sequentially, about 3.8 times faster on 12 cores. The 12-chunk pool took 816 ms, slower than the stream, because the chunks were unequal: the higher number ranges hold more work, so one chunk finished late. 5,000 blocking calls took 289 ms on virtual threads. The two-service combine took 304 ms, and the failing scope returned in 107 ms.
Why: Each tool matched its kind of work. The pool result is a lesson too: fixed chunks are fragile when the work is uneven, and the stream's work stealing handled it better. These timings come from one run on this machine, with the machine shared with other work.
Tool chosen by fashion
Virtual threads for everything, including CPU work.
try (var ex = Executors
.newVirtualThreadPerTaskExecutor()) {
for (var chunk : chunks)
ex.submit(() -> crunch(chunk));
} // no faster than 12 platform threadsTool chosen by the work
CPU work on a stream, waiting on virtual threads.
long n = IntStream.range(0, N)
.parallel().filter(this::prime)
.count(); // CPU: cores
// waits: virtual threads + SemaphoreThe shift: Ask what the work is waiting for, and pick the tool that matches the answer.
Land it I choose by what the work spends its time on: cores for CPU, virtual threads for waiting, CompletableFuture for composition with fallbacks, structured concurrency for all-or-nothing, and atomics or locks for shared data.
- "What if the workload is mixed, part CPU and part waiting?"
-
Separate the two parts, and give each its own resource. A common shape is a request on a virtual thread that waits on I/O, and when it needs heavy computation it hands that step to a fixed pool near the core count and waits for the result.
The wait for the pool is cheap on a virtual thread, and the heavy step stays limited to the cores. This avoids two problems at once: CPU work starving the carriers, and I/O work being limited by a small CPU pool.
The same idea works with
CompletableFuture:supplyAsync(cpuStep, cpuPool)andsupplyAsync(ioStep, ioExecutor)in one pipeline, each on the executor that suits it.Measure each part's share of the time first, so you know which side is the bottleneck.
- "How do I decide the size of each pool?"
-
From the limiting resource. For CPU work the limit is cores, so a pool of about
cores(12 here). For I/O on virtual threads there is no pool, and the limit is the downstream, so aSemaphoresized from what it can take (a database pool of 20 means about 20 permits).For a fixed pool of platform threads doing I/O (on Java 17 and older), use the formula cores times (1 + wait / compute), then test under load and watch queue length and latency.
- Find the limit: cores, connection pool, remote rate limit.
- Set the concurrency to it: pool size or semaphore permits.
- Bound the backlog: a bounded queue and a rejection policy (Q75, Q76).
E3 Q184 has the worked numbers.
- "Which choice is the easiest to get wrong?"
-
The parallel stream, because it looks free. Adding
.parallel()to a pipeline with a shared mutable collection, a blocking call, a small data set or an ordered terminal operation makes it wrong or slower (Q56 to Q60). It also uses the shared common pool, so it can slow unrelated code.The second is
CompletableFuturewithout an executor or a final handler: blocking calls land on the common pool, and failures vanish (Q89, Q92).The third is virtual threads without a limit on the downstream, which just moves the queue to a service that cannot take it (Q95).
My rule is to treat each tool's convenience as a warning: the easier it is to switch on, the more I check that the conditions hold, and measure.
- "How would I explain the choice to a junior developer in one minute?"
-
Ask three questions in order.
- Is it computing or waiting? Computing: use the cores, with a parallel stream or a pool sized to them. Waiting: use virtual threads.
- Do the pieces depend on each other? Independent pieces that you combine:
CompletableFuture(or structured concurrency when final). A single chain of steps needs no concurrency at all. - What is shared? A counter: an atomic. Several fields that must agree: a lock. Nothing shared: best of all.
Then add the safety nets: a timeout on every wait, a limit on every downstream, a name on every thread and a handler on every future.
If they remember "what is it waiting for?", they will usually choose well.
16 · RecapWhat You Can Do Now
- You can say which Java release added each feature you use (lambdas and streams in 8,
varin 10, switch expressions in 14, text blocks in 15, records in 16, sealed classes in 17, virtual threads in 21, gatherers in 24, scoped values in 25), and prove it withjavac --release - You can build a stream pipeline and say what runs when: lazy intermediate steps, a terminal operation that pulls one element at a time, short-circuiting, and why
sortedmust see everything first - You can group, partition and merge with collectors (
toMapwith a merge function,groupingBywith downstream collectors,teeing) and write the same report with a plain loop to compare - You can decide when a parallel stream helps (large N, costly per element, splittable source, no shared state, no blocking) and show the measurement that proves it
- You can explain why
count++loses updates, why a plain flag may never be seen, and fix each with the smallest tool:synchronized,volatile, an atomic orLongAdder - You can find and fix a deadlock by lock ordering, read the "Found one Java-level deadlock" banner in a thread dump, and use
tryLockwith a timeout where no order exists - You can build a bounded
ThreadPoolExecutor, predict what a task meets in order (core, queue, max, rejection), handleFuturefailures and timeouts, and shut a pool down cleanly - You can compose
CompletableFuturework (thenComposeagainstthenCombine), say which thread runs each step, end every chain with a handler, and cap a fan-out with a timeout and a fallback - You can choose between a parallel stream, a sized pool,
CompletableFuture, virtual threads and structured concurrency by what the work waits on, and name what pinning was and what changed in Java 24
Close the page and write down, from memory: the Java version that introduced records, var, text blocks, virtual threads and gatherers; then draw the path a task takes through a ThreadPoolExecutor with core 2, max 4 and a queue of 2, and say which of eight submitted tasks are rejected.
Then pick one lost-update bug and one visibility bug from this chapter and name the smallest fix for each. When that feels easy, reach for the interview round: E3 Q141–Q180 and E3 Q181–Q220, and E2's memory model for the rules underneath.
17 · SummaryAll 27 Idioms on One Page
Every idiom in this chapter, each with the problem it solves and the solution in one line. Click an idiom name to jump to its full breakdown. A table of what each Java release added follows.
04 · Lambdas, functional interfaces and Optional
| Idiom | Problem | Solution |
|---|---|---|
| orElseGet, not orElse | orElse(expensive()) runs the call every time, even when the Optional already has a value. | Use orElseGet(() -> expensive()) so the supplier runs only when the Optional is empty. |
| Optional for return values only | Optional used as a field, a parameter or a collection element adds wrapping, nested nulls and confusion. | Return Optional from methods that may have no answer; use overloads, empty collections or plain null checks elsewhere. |
| Method reference | A lambda that only forwards to one method is noisy and hides the name of what it calls. | Write Order::customer or String::trim when the lambda just calls that method. |
05 · How a stream pipeline runs
| Idiom | Problem | Solution |
|---|---|---|
| No side effects in the pipeline | A lambda that adds to an outside list or map works sequentially and breaks, or throws, in parallel. | Let the pipeline return the result with collect or reduce, and keep stage lambdas free of outside state. |
| Primitive streams | Stream<Integer> boxes every element, which costs time and memory on large data. | Switch early with mapToInt or mapToLong and finish with sum, average or max. |
| Short-circuit early | The pipeline reads the whole source, or an infinite one, although only a few elements are needed. | End with findFirst, anyMatch, limit or takeWhile so the pull stops early. |
06 · Collectors
| Idiom | Problem | Solution |
|---|---|---|
| toMap with a merge function | toMap throws IllegalStateException: Duplicate key when two elements share a key. | Pass a merge function such as Integer::sum, and a LinkedHashMap::new supplier when order matters. |
| groupingBy with a downstream collector | Grouping into lists and then looping to count or sum repeats work and loses the single pass. | Add a downstream collector (counting, summingInt, mapping) and TreeMap::new for sorted keys. |
| teeing | Two results from one stream (minimum and maximum) seem to need two passes, but a stream can be consumed once. | Use Collectors.teeing(c1, c2, merger) to run both collectors in one pass. |
07 · Parallel streams
| Idiom | Problem | Solution |
|---|---|---|
| Parallel only when it pays | .parallel() added by habit makes small, blocking or ordered pipelines slower. | Use it for large data with costly per-element work, a splittable source, no shared state and no blocking, and measure. |
| No shared state in parallel | parallelStream().forEach into a shared HashMap loses updates or throws ConcurrentModificationException. | Collect with groupingBy or toMap, which build thread-confined partial results and merge them. |
08 · Threads from zero
| Idiom | Problem | Solution |
|---|---|---|
| start, not run | Calling run() executes the body on the caller, so "parallel" work runs one after another. | Call start() (then join() if needed), or better, submit the task to an executor. |
| Volatile flag | A plain stop flag may never be seen by the worker, which spins forever. | Declare the flag volatile, or cancel with interrupt() and check isInterrupted(). |
09 · Synchronization
| Idiom | Problem | Solution |
|---|---|---|
| Synchronized counter | count++ from several threads loses updates because it is read, add, write. | Guard the update with synchronized (one lock for the whole action) so the total is exact. |
| Lock ordering | Two threads take two locks in opposite order and wait for each other forever. | Always acquire locks in one global order, for example by account id. |
| Atomic counter | A lock around a single counter is slower than it needs to be under contention. | Use AtomicLong, or LongAdder for heavy write contention, for one variable. |
| tryLock with a timeout | A thread waits forever for a lock whose owner is stuck. | Use ReentrantLock.tryLock(time, unit), give up, and retry or fail with a clear error. |
10 · Executors and the coordination toolkit
| Idiom | Problem | Solution |
|---|---|---|
| Bounded pool | newFixedThreadPool hides an unbounded queue that turns overload into OutOfMemoryError. | Build a ThreadPoolExecutor with a bounded queue, named threads and a rejection policy chosen on purpose. |
| Callable and Future | A Runnable cannot return a value or throw a checked exception, so results travel through shared state. | Submit a Callable, collect the Future with a timeout, and unwrap ExecutionException. |
| Clean shutdown | A forgotten pool keeps the JVM alive, and an abrupt stop loses queued work. | Call shutdown, awaitTermination with a limit, then shutdownNow; since Java 19 use try-with-resources. |
| Name your threads | Default names such as pool-3-thread-7 say nothing in a dump or a log. | Give each pool a ThreadFactory such as Thread.ofPlatform().name("notify-", 0).factory(). |
| computeIfAbsent | Check-then-put on a concurrent map computes the same value several times. | Use map.computeIfAbsent(key, fn) so the function runs once per key, and keep it short. |
11 · CompletableFuture
| Idiom | Problem | Solution |
|---|---|---|
| Fan-out with a timeout | Calling services one after another adds their delays, and a slow one hangs the request. | Start all calls first on a named executor, combine them, and add completeOnTimeout and orTimeout. |
| Own executor | Blocking calls in supplyAsync land on the shared common pool and starve parallel streams. | Pass your own named, bounded executor to supplyAsync and the *Async methods. |
| Handle errors | A failed stage is stored silently, so the request hangs or errors with a clean log. | End every chain with handle or whenComplete, unwrap CompletionException, and add a timeout. |
12 · Virtual threads and structured concurrency
| Idiom | Problem | Solution |
|---|---|---|
| Virtual thread per task | A fixed pool of 200 caps blocking calls at 200 at a time, and requests queue. | Use Executors.newVirtualThreadPerTaskExecutor(): one cheap thread per task, never pooled. |
| Semaphore limit | With no pool size, a burst of virtual threads can overwhelm a fragile downstream. | Put a Semaphore sized to what the downstream can take around the call, released in finally. |
Versions at a glance
| Version | Year | LTS | Headline features |
|---|---|---|---|
| Java 8 | Mar 2014 | LTS | Lambdas, method references, Stream API, default and static interface methods, Optional, java.time, CompletableFuture, LongAdder |
| Java 9 | Sep 2017 | Modules (JPMS), JShell, List.of/Map.of, private interface methods, takeWhile/dropWhile, CompletableFuture.orTimeout, G1 default | |
| Java 10 | Mar 2018 | var, List.copyOf, Collectors.toUnmodifiableList, Optional.orElseThrow() | |
| Java 11 | Sep 2018 | LTS | Standard HttpClient, String.isBlank/strip/repeat, Files.readString, single-file launch, Predicate.not |
| Java 12 | Mar 2019 | Collectors.teeing, String.indent/transform, switch expressions (preview) | |
| Java 13 | Sep 2019 | Text blocks (preview), switch yield (preview) | |
| Java 14 | Mar 2020 | Switch expressions final, helpful NullPointerExceptions, records and instanceof patterns (preview) | |
| Java 15 | Sep 2020 | Text blocks final, String.formatted, sealed classes (preview), ZGC and Shenandoah production-ready | |
| Java 16 | Mar 2021 | Records final, instanceof patterns final, Stream.toList(), mapMulti, strong encapsulation (JEP 396) | |
| Java 17 | Sep 2021 | LTS | Sealed classes final, pattern matching for switch (preview), internals sealed off (JEP 403), RandomGenerator |
| Java 18 | Mar 2022 | UTF-8 by default, jwebserver, @snippet in Javadoc | |
| Java 19 | Sep 2022 | Virtual threads (preview), structured concurrency (incubator), record patterns (preview), ExecutorService is AutoCloseable | |
| Java 20 | Mar 2023 | Scoped values (incubator), further previews | |
| Java 21 | Sep 2023 | LTS | Virtual threads final, sequenced collections, record patterns final, pattern matching for switch final, generational ZGC |
| Java 22 | Mar 2024 | Unnamed variables and patterns _ final, Foreign Function and Memory API final, multi-file source launch | |
| Java 23 | Sep 2024 | Markdown doc comments (///), ZGC generational by default, primitive patterns (preview) | |
| Java 24 | Mar 2025 | Stream gatherers final, class-file API final, virtual threads no longer pin on synchronized (JEP 491), AOT class loading | |
| Java 25 | Sep 2025 | LTS | Scoped values final, compact source files and instance main final, module imports final, flexible constructor bodies final |
| Java 26 | Mar 2026 | HTTP/3 in HttpClient, final-means-final warnings (JEP 500), AOT object caching with any GC; no new final syntax | |
| Java 27 | Sep 2026 | G1 default in all environments, compact object headers by default, post-quantum TLS hybrid key exchange; no new final syntax |