Mastering Java 21: Key Features, Enhancements, and Code Examples

Java 21: Key Features, Enhancements, and Code Examples

Java 21, released in September 2023, is a Long-Term Support (LTS) release and comes with major improvements that make Java more expressive, scalable, and developer-friendly.

Letโ€™s dive into the top features of Java 21 with code examples and use cases.


๐Ÿš€ 1. Virtual Threads (Project Loom)

Problem: Traditional threads are expensive and limited in scalability.

Solution: Virtual threads are lightweight threads that improve concurrency performance and reduce the overhead of using many threads.

public class VirtualThreadDemo {
    public static void main(String[] args) {
        Runnable task = () -> System.out.println("Running in " + Thread.currentThread());
        
        // Launching 1 million virtual threads
        for (int i = 0; i < 1000000; i++) {
            Thread.startVirtualThread(task);
        }
    }
}
Note: Virtual threads use the same API as platform threads but are scheduled by the JVM and not tied to OS threads.

๐ŸŽฏ 2. Pattern Matching for switch (Finalized)

This allows matching object types in switch expressions and performing specific actions based on type.

static String formatter(Object obj) {
    return switch (obj) {
        case Integer i -> "Integer: " + i;
        case String s  -> "String: " + s.toUpperCase();
        case null      -> "Null value";
        default        -> "Unknown type";
    };
}
Why it matters: Cleaner and more readable type-specific logic.

๐Ÿ“ฆ 3. Record Patterns (Finalized)

Allows destructuring records directly in pattern matching expressions.

record Person(String name, int age) {}

static void printInfo(Object obj) {
    if (obj instanceof Person(String name, int age)) {
        System.out.println(name + " is " + age + " years old.");
    }
}
Use case: Simplifies working with data records by extracting values directly.

๐Ÿ’ฌ 4. String Templates (Preview)

Provides cleaner and safer string interpolation using templates.

import static java.util.FormatProcessor.FMT;

String name = "Java";
String message = FMT."Hello, \{name}!";
System.out.println(message);
Note: This is a preview feature and must be enabled using --enable-preview.

โฒ 5. Sequenced Collections

Java 21 adds a new interface SequencedCollection with methods like reversed(), getFirst(), getLast().

List<String> list = List.of("A", "B", "C");
System.out.println(list.reversed()); // [C, B, A]
Why it matters: Uniform access to elements from both ends in lists, sets, and maps.

๐Ÿ” 6. Unnamed Patterns & Variables (Preview)

Simplify pattern matching where you donโ€™t need to name all variables.

if (obj instanceof Person(String _, int age)) {
    System.out.println("Age is " + age);
}
Benefit: Cleaner, intention-revealing code without unused variables.

๐Ÿ•น 7. Scoped Values (Incubator)

A safer and faster alternative to ThreadLocal for sharing values between methods in the same thread (including virtual threads).

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

ScopedValue.where(USER_ID, "abc123").run(() -> {
    System.out.println(USER_ID.get());
});

๐ŸŒ 8. Deprecations and Removals

  • Final removal of the Security Manager.
  • Some internal APIs moved/removedโ€”clean up old libraries.

๐Ÿ“… 9. New DateTime Parsing Enhancements

Improved parsing in java.time.format with better error messages and corner-case handling.


โš™๏ธ How to Enable Preview Features

To test preview features like string templates, use:

javac --enable-preview --release 21 MyApp.java
java --enable-preview MyApp

๐Ÿง  Final Thoughts

  • Java 21 is a significant LTS releaseโ€”upgrade if you havenโ€™t!
  • Virtual threads are a game-changer for high-concurrency applications.
  • Pattern matching and record patterns boost developer productivity.
  • New collection and language enhancements bring Java closer to modern languages like Kotlin and Scala.

๐Ÿ”— Related Posts

๐Ÿ“˜ Java 21 Record Patterns

Explore one of the most powerful features in Java 21 for destructuring and matching records.

๐Ÿงช Java 21 Interview Questions

Practice questions based on new features like sequenced collections and virtual threads.

๐Ÿ”€ Mastering Java Streams

Modern Java flows often pair pattern matching with map/filter/reduce operations.

๐Ÿ’ก Exception Handling Best Practices

Complement new language features with clean, effective error handling techniques.