A Look at the Newest Features
Java 21, released in September 2023, brings several exciting features that continue to evolve the language. Let's explore what's new.
Virtual Threads (JEP 444)
Virtual threads are now a permanent feature after being previewed in previous versions:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
}
Key benefits:
- Lightweight threads managed by the JVM
- Dramatically reduces memory footprint
- Simplifies concurrent programming
Pattern Matching for switch (JEP 441)
Switch expressions get more powerful with pattern matching:
String formatted = 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);
default -> obj.toString();
};
Record Patterns (JEP 440)
Deconstruct records with elegant pattern matching:
record Point(int x, int y) {}
static void printSum(Object obj) {
if (obj instanceof Point(int x, int y)) {
System.out.println(x + y);
}
}
Sequenced Collections (JEP 431)
New interfaces for collections with defined encounter order:
interface SequencedCollection<E> extends Collection<E> {
// New methods
void addFirst(E);
void addLast(E);
E getFirst();
E getLast();
E removeFirst();
E removeLast();
}
String Templates (Preview) (JEP 430)
Safer string interpolation:
String name = "Joan";
String info = STR."My name is \{name}";
Scoped Values (Preview) (JEP 446)
Better alternative to thread locals for sharing immutable data:
final static ScopedValue<String> NAME = ScopedValue.newInstance();
ScopedValue.where(NAME, "value").run(() -> {
// NAME is bound here
});
Performance Improvements
- Generational ZGC (JEP 439) improves garbage collection
- Key encapsulation mechanism API (JEP 452) for post-quantum cryptography
- Deprecation of Windows 32-bit x86 port
Summary
Java 21 continues the modernization of the platform with:
- Production-ready virtual threads for scalable concurrency
- Enhanced pattern matching capabilities
- New collection interfaces
- Preview features for future enhancements
These changes make Java more expressive, performant, and maintainable while keeping its hallmark stability.