Priyanshu Mishra

Top Features in Java 21 You Must Know

A deep dive into the game-changing features of Java 21, including Virtual Threads, Pattern Matching, Sequenced Collections, and more.

Top Features in Java 21 You Must Know โ˜•๏ธ

Java 21 is a landmark Long-Term Support (LTS) release that fundamentally changes how we write and scale Java applications. It moves several preview features to standard and introduces powerful new tools for concurrency and data handling.

In this comprehensive guide, we'll explore the most impactful features that every Java developer should master.

1. Virtual Threads (Project Loom) ๐Ÿงต

Virtual threads are arguably the most significant update to Java since Lambdas in Java 8. They decouple the Java thread from the operating system thread, allowing you to create millions of threads with minimal overhead.

The Problem with Platform Threads

Traditionally, Java threads were 1:1 mapped to OS threads. OS threads are expensive to create and limited in number (usually a few thousand). This made the "thread-per-request" model unscalable for high-throughput applications.

The Virtual Thread Solution

Virtual threads are managed by the JVM, not the OS. They are cheap to create and block efficiently.

// Creating 10,000 virtual threads is trivial
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i -> {
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1)); // The underlying OS thread is NOT blocked here
            return i;
        });
    });
}

Key Takeaway

You no longer need complex reactive frameworks (like WebFlux) just to handle high concurrency. You can write simple, blocking, imperative code that scales like reactive code.

2. Pattern Matching for Switch ๐Ÿ”€

Pattern matching for switch reduces boilerplate and makes type-checking logic much cleaner. It allows you to match against types directly in case labels.

Before Java 21

if (obj instanceof Integer i) {
    return String.format("int %d", i);
} else if (obj instanceof Long l) {
    return String.format("long %d", l);
} else {
    return obj.toString();
}

With Java 21

static String formatValue(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        case null      -> "null";
        default        -> obj.toString();
    };
}

You can even use Guarded Patterns with the when clause:

case String s when s.length() > 10 -> "Long string: " + s;

3. Record Patterns ๐Ÿ“ฆ

Record patterns allow you to deconstruct record values directly. This is incredibly powerful when combined with switch expressions and nested data structures.

record Point(int x, int y) {}
record ColoredPoint(Point p, String color) {}

static void printPoint(Object obj) {
    if (obj instanceof ColoredPoint(Point(int x, int y), String color)) {
        System.out.println("Point at (" + x + ", " + y + ") with color " + color);
    }
}

4. Sequenced Collections ๐Ÿ“š

For years, Java's collection framework lacked a unified way to access the first and last elements. Java 21 introduces SequencedCollection, SequencedSet, and SequencedMap.

Unified API

No more list.get(0) or set.iterator().next().

List<String> list = new ArrayList<>();
list.addLast("Java");
list.addFirst("Hello");

String first = list.getFirst(); // "Hello"
String last = list.getLast();   // "Java"

List<String> reversed = list.reversed();

This applies to ArrayList, LinkedList, LinkedHashSet, TreeSet, LinkedHashMap, and TreeMap.

5. String Templates (Preview) ๐Ÿ“

Note: This is a preview feature in Java 21.

String Templates allow for safe and readable string interpolation, similar to f-strings in Python or template literals in JavaScript.

String name = "Priyanshu";
int age = 25;

// STR is a template processor provided by Java
String message = STR."Hello \{name}, you are \{age} years old.";

Unlike simple string concatenation, template processors can validate and sanitize inputs (e.g., preventing SQL injection with a hypothetical SQL processor).

6. Unnamed Classes and Instance Main Methods (Preview) ๐Ÿš€

Java 21 makes it easier for beginners to start coding without understanding public static void main(String[] args) or class declarations.

The Old Way

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

The New Way (Preview)

void main() {
    System.out.println("Hello, World!");
}

Conclusion

Java 21 is a massive leap forward. Virtual threads alone justify the upgrade for many server-side applications. Combined with the expressiveness of pattern matching and the convenience of sequenced collections, Java 21 is the most exciting release in years.

Upgrade Now

If you are still on Java 8 or 11, plan your migration to Java 21 today. The performance and productivity gains are too good to ignore.