Java 21: The Features That Matter for Backend Engineers
Virtual threads, record patterns, sequenced collections — Java 21 is a landmark LTS release. Here's what to adopt now and what to watch for in interviews.
Java 21: The Features That Matter for Backend Engineers
Java 21 is a Long-Term Support (LTS) release — the first since Java 17. It finalises several features that have been previewing for years.
Virtual Threads (Project Loom)
Virtual threads are lightweight, JVM-managed threads that cost ~1KB of heap instead of ~1MB for a platform thread. You can have millions.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 100_000).forEach(i ->
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
})
);
}
// All 100,000 tasks complete in ~1 second
For Spring Boot, one property enables them everywhere:
spring:
threads:
virtual:
enabled: true
Interview takeaway: Virtual threads shine for I/O-bound workloads (REST calls, DB queries). For CPU-bound work, they offer no benefit.
Records
Immutable data carriers without boilerplate:
record Point(int x, int y) {}
record User(String name, String email) {
// Compact constructor for validation
User {
Objects.requireNonNull(name, "name must not be null");
}
}
Pattern Matching for switch
String format(Object obj) {
return switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
case null -> "null";
default -> "Unknown: " + obj;
};
}
Sequenced Collections
New SequencedCollection interface standardises first/last access across all ordered collections:
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.getFirst(); // "a"
list.getLast(); // "c"
list.reversed(); // ["c", "b", "a"] (view, not copy)