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);
}
}
}
๐ฏ 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";
};
}
๐ฆ 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.");
}
}
๐ฌ 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);
--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]
๐ 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);
}
๐น 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.