Upgrade from Java 8: 8 Powerful Features in Java 21 You Should Know
The article examines why many projects still cling to Java 8 and demonstrates eight transformative Java 21 features—including records, sealed classes, pattern‑matching for instanceof, switch expressions, text blocks, virtual threads, structured concurrency, and enhanced APIs—showing code examples and the benefits they bring to performance, readability, and maintainability.
Although Java 8 was released twelve years ago and more than 70% of enterprise projects still run on it due to migration cost and lack of awareness, Java 21 (the current long‑term support baseline, GA version 25) arrives with a suite of major language enhancements that dramatically improve performance, developer productivity, and code maintainability.
1. Records (Data‑carrier classes)
Records are special classes designed to hold immutable data. They replace verbose POJOs that only store fields, provide getters, and override equals(), hashCode(), and toString().
Traditional POJO :
// Traditional POJO (verbose and repetitive)
public class User {
private final String name;
private final int age;
public User(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public int getAge() { return age; }
@Override public boolean equals(Object o) { /* ... */ }
@Override public int hashCode() { /* ... */ }
@Override public String toString() { /* ... */ }
}Modern record : public record User(String name, int age) {} Advantages: perfect for DTOs and API responses, immutable (thread‑safe) by default, and eliminates boilerplate.
2. Sealed Classes
Sealed classes let you precisely control which classes may extend or implement a type, avoiding the two extremes of fully open inheritance or awkward private constructors.
Example (payment services):
// Sealed interface defining permitted subclasses
public sealed interface IPaymentService permits WeiXin, AliPay, BankPay {}
public final class WeiXinService implements IPaymentService {}
public final class AliPayService implements IPaymentService {}
public final class BankPayService implements IPaymentService {}Attempting to add another implementation results in a compile‑time error, as shown in the accompanying screenshot.
3. instanceof Pattern Matching
Java 21 allows pattern matching directly in the instanceof check, removing the need for a separate cast.
Traditional:
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}Modern:
if (obj instanceof String s) {
System.out.println(s.length());
}This reduces redundant code and eliminates cast‑related errors.
4. Switch Pattern Matching
The enhanced switch can handle type patterns, sealed‑class hierarchies, and does not require a default when the compiler can verify exhaustiveness.
static String processPayment(IPaymentService payment) {
return switch (payment) {
case WeiXinService wx -> "微信支付";
case AliPayService as -> "支付宝支付";
case BankPayService bps -> "银联支付";
};
}If a new payment implementation is added without updating the switch, the compiler reports an error, ensuring compile‑time safety.
5. Text Blocks
Multi‑line string literals (text blocks) replace cumbersome concatenation.
Traditional:
String json = "{
" +
" \"name\": \"Pack_xg\",
" +
" \"title\": \"Spring Boot3实战案例300讲\"
" +
"}";Modern:
String json = """
{
"name": "Pack_xg",
"title": "Spring Boot3实战案例300讲"
}
""";6. Virtual Threads
Virtual threads are lightweight threads managed by the JVM rather than the OS, enabling millions of concurrent tasks without thread‑pool tuning.
Traditional approaches rely on limited OS threads or complex reactive frameworks, leading to callback hell.
Example:
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
Thread.sleep(1000);
System.out.println("执行网络IO, 数据库查询等IO耗时的操作");
});
}Virtual threads allow simple blocking code while achieving massive concurrency.
7. Structured Concurrency
Structured concurrency treats a group of related tasks as a single logical unit, automatically cancelling sibling tasks on failure and centralising error handling.
static RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) throws Exception {
ExecutorService es = Executors.newFixedThreadPool(2);
Future<Object> userInfo = es.submit(UnstructuredConcurrentDemo::queryUserInfo);
Future<Object> stock = es.submit(UnstructuredConcurrentDemo::queryStock);
System.out.printf("执行结果:用户信息:%s%n", userInfo.get().toString());
System.out.printf("执行结果:库存信息:%s%n", stock.get().toString());
}
public static Object queryUserInfo() {
return restTemplate.getForObject("http://localhost:8080/demos/userinfo", String.class);
}
public static Object queryStock() {
return restTemplate.getForObject("http://localhost:8080/demos/stock", String.class);
}The output shows successful retrieval of user and stock information, demonstrating how structured concurrency simplifies coordination and error propagation.
8. Enhanced APIs
Optional.ifPresentOrElse– execute different actions based on presence, reducing verbose if‑else blocks.
New stream collectors such as Collectors.teeing() – simplify complex aggregation.
Improved NPE messages – directly indicate the null variable name.
Immutable factories List.of() / Map.of() – create unmodifiable collections without extra copying.
Strong encapsulation of JDK internals – prevents reflective access, enhancing long‑term stability.
These preview features in Java 21 collectively shift Java development toward a more concise, safe, and high‑performance paradigm.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
