Java 21 Features

Java 21 Features: The Complete Guide for Developers

Java 21, released in September 2023, is a major Long-Term Support (LTS) release. It brings cutting-edge features like virtual threads, record patterns, string templates, and more. Let’s dive into what’s new in Java 21!

1. Virtual Threads (JEP 444)

Part of Project Loom, virtual threads are lightweight threads that scale your applications with minimal changes.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(() -> System.out.println("Hello from a virtual thread!"));
}

They’re ideal for handling high-concurrency applications like web servers.

2. Record Patterns (JEP 440)

Pattern matching now supports records, making deconstruction more elegant:

record Point(int x, int y) {}

static void print(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        System.out.println("x = " + x + ", y = " + y);
    }
}

3. Pattern Matching for switch (JEP 441)

Switch can now use type patterns, making decision trees concise and type-safe:

static String handleShape(Object shape) {
    return switch (shape) {
        case Circle c -> "Circle radius: " + c.radius();
        case Rectangle r -> "Rectangle area: " + (r.w() * r.h());
        default -> "Unknown shape";
    };
}

4. String Templates (Preview) (JEP 430)

String interpolation comes to Java with STR templates:

String name = "Java";
String greeting = STR."Hello, \{name}!";
System.out.println(greeting);

This feature is in preview but hugely anticipated!

5. Unnamed Classes and Instance main() (Preview)

You can now write minimal Java programs with no class declaration:

void main() {
    System.out.println("Minimal Java app!");
}

Perfect for scripts, learning, or quick prototyping.

6. Scoped Values (Preview) (JEP 446)

Scoped values allow safe, efficient sharing of data between threads — especially useful with virtual threads:

ScopedValue<String> USERNAME = ScopedValue.newInstance();

ScopedValue.where(USERNAME, "alice").run(() -> {
    System.out.println("Hello " + USERNAME.get());
});

7. Structured Concurrency (Preview) (JEP 453)

Makes managing concurrent tasks easier and safer by treating them as a single unit of work:

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Future<String> user = scope.fork(() -> fetchUser());
    Future<String> orders = scope.fork(() -> fetchOrders());

    scope.join();
    scope.throwIfFailed();

    return user.result() + orders.result();
}

📌 Final Thoughts

Java 21 modernizes the platform with features developers have wanted for years. If you’re using Java 17 or earlier, this LTS release is a solid upgrade.

Java is more expressive, scalable, and fun than ever. Time to make the move!

Comments

Popular posts from this blog

Spring Boot with AI

Voice & Chatbots – AI-Assisted Conversational Apps

Java 17 Features