Skip to content

Java 18-21新特性

Java 18新特性

默认UTF-8编码

java
import java.nio.charset.Charset;

public class Java18EncodingDemo {
    public static void main(String[] args) {
        // Java 18+:默认字符集为UTF-8
        System.out.println(Charset.defaultCharset());  // UTF-8
        
        // 读取文件默认使用UTF-8
        // 之前可能需要指定编码
    }
}

简单Web服务器

bash
# 启动简单Web服务器
java -m jdk.httpserver -p 8080

# 指定根目录
java -m jdk.httpserver -p 8080 -d /path/to/root
java
import com.sun.net.httpserver.SimpleFileServer;
import java.net.InetSocketAddress;
import java.nio.file.Path;

public class SimpleWebServerDemo {
    public static void main(String[] args) {
        var server = SimpleFileServer.createFileServer(
            new InetSocketAddress(8080),
            Path.of("."),
            SimpleFileServer.OutputLevel.VERBOSE
        );
        server.start();
    }
}

代码片段@snippet

java
/**
 * 使用示例:
 * {@snippet :
 * var list = List.of("A", "B", "C");
 * list.forEach(System.out::println);
 * }
 * 
 * 高亮代码:
 * {@snippet :
 * public void hello() {
 *     System.out.println("Hello"); // @highlight substring="println"
 * }
 * }
 * 
 * 替换代码:
 * {@snippet :
 * var list = List.of("A", "B"); // @replace substring='"A", "B"' replacement="..."
 * }
 */
public class SnippetDemo {
}

Java 19新特性

虚拟线程(预览)

java
import java.util.concurrent.Executors;

public class VirtualThreadDemo {
    public static void main(String[] args) throws Exception {
        // 创建虚拟线程
        Thread vThread = Thread.ofVirtual().start(() -> {
            System.out.println("虚拟线程: " + Thread.currentThread());
        });
        
        // 使用虚拟线程工厂
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10000; i++) {
                executor.submit(() -> {
                    Thread.sleep(1000);
                    return "Done";
                });
            }
        }
        
        // 创建虚拟线程并等待
        Thread.ofVirtual().name("my-virtual-thread").start(() -> {
            System.out.println("Hello from virtual thread");
        }).join();
    }
}

结构化并发(预览)

java
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;

public class StructuredConcurrencyDemo {
    public static void main(String[] args) throws Exception {
        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
            Future<String> user = scope.fork(() -> fetchUser());
            Future<Integer> order = scope.fork(() -> fetchOrder());
            
            scope.join();           // 等待所有任务
            scope.throwIfFailed();  // 如果有失败则抛出异常
            
            String userName = user.resultNow();
            Integer orderId = order.resultNow();
            
            System.out.println(userName + " - " + orderId);
        }
    }
    
    static String fetchUser() { return "张三"; }
    static int fetchOrder() { return 12345; }
}

值类型(预览)

java
// 预览特性,用于高性能场景
// 类似于C#的struct

Java 20新特性

虚拟线程增强

java
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Java20VirtualThreadDemo {
    public static void main(String[] args) {
        // 创建虚拟线程工厂
        ThreadFactory factory = Thread.ofVirtual().factory();
        
        // 使用工厂创建线程池
        try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
            // 提交任务
        }
        
        // 虚拟线程的属性
        Thread vThread = Thread.ofVirtual()
            .name("worker-", 0)
            .unstarted(() -> System.out.println("Working"));
        
        System.out.println(vThread.isVirtual());  // true
        vThread.start();
    }
}

记录模式(预览)

java
public record Point(int x, int y) {}
public record Rectangle(Point upperLeft, Point lowerRight) {}

public class RecordPatternDemo {
    public static void main(String[] args) {
        Object obj = new Point(10, 20);
        
        // 记录模式匹配
        if (obj instanceof Point(int x, int y)) {
            System.out.println("x=" + x + ", y=" + y);
        }
        
        // 嵌套记录模式
        Object rect = new Rectangle(new Point(0, 10), new Point(20, 0));
        if (rect instanceof Rectangle(Point(int x1, int y1), Point(int x2, int y2))) {
            System.out.println("Rectangle: (" + x1 + "," + y1 + ") - (" + x2 + "," + y2 + ")");
        }
    }
}

Java 21新特性(LTS)

虚拟线程正式版

java
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Java21VirtualThreadDemo {
    public static void main(String[] args) throws Exception {
        // 方式1:直接创建
        Thread vThread1 = Thread.ofVirtual().start(() -> {
            System.out.println("虚拟线程执行");
        });
        
        // 方式2:使用工厂
        ThreadFactory factory = Thread.ofVirtual().factory();
        Thread vThread2 = factory.newThread(() -> {
            System.out.println("工厂创建的虚拟线程");
        });
        vThread2.start();
        
        // 方式3:Executors
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            executor.submit(() -> "Hello");
        }
        
        // 虚拟线程非常适合IO密集型任务
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10000; i++) {
                executor.submit(() -> {
                    // 模拟IO操作
                    Thread.sleep(1000);
                    return "Done";
                });
            }
        }
    }
}

结构化并发

java
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.Future;

public class Java21StructuredConcurrencyDemo {
    record Response(String user, int order) {}
    
    Response handle() throws Exception {
        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
            Future<String> user = scope.fork(() -> fetchUser());
            Future<Integer> order = scope.fork(() -> fetchOrder());
            
            scope.join();
            scope.throwIfFailed();
            
            return new Response(user.resultNow(), order.resultNow());
        }
    }
    
    // 其他策略
    Response handleWithTimeout() throws Exception {
        try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
            scope.fork(() -> fetchFromServer1());
            scope.fork(() -> fetchFromServer2());
            
            scope.joinUntil(java.time.Instant.now().plusSeconds(5));
            
            return new Response(scope.resultNow(), 0);
        }
    }
    
    String fetchUser() { return "张三"; }
    int fetchOrder() { return 12345; }
    String fetchFromServer1() { return "Server1"; }
    String fetchFromServer2() { return "Server2"; }
}

模式匹配增强

java
public class PatternMatchingDemo {
    public static void main(String[] args) {
        Object obj = "Hello";
        
        // 记录模式
        if (obj instanceof String s && s.length() > 3) {
            System.out.println(s.toUpperCase());
        }
        
        // switch模式匹配
        String result = switch (obj) {
            case Integer i -> "整数: " + i;
            case Long l -> "长整数: " + l;
            case Double d -> "浮点数: " + d;
            case String s -> "字符串: " + s;
            case null -> "null";
            default -> "未知类型";
        };
        
        // 带守卫的模式
        String categorized = switch (obj) {
            case String s when s.length() > 10 -> "长字符串";
            case String s when s.length() > 5 -> "中等字符串";
            case String s -> "短字符串";
            default -> "非字符串";
        };
    }
}

字符串模板(预览)

java
public class StringTemplateDemo {
    public static void main(String[] args) {
        String name = "张三";
        int age = 25;
        
        // 传统方式
        String s1 = "姓名: " + name + ", 年龄: " + age;
        String s2 = String.format("姓名: %s, 年龄: %d", name, age);
        
        // Java 21+:字符串模板(预览)
        // String s3 = STR."姓名: \{name}, 年龄: \{age}";
        
        // 多行模板
        String json = """
            {
                "name": "%s",
                "age": %d
            }
            """.formatted(name, age);
        
        // 字符串模板版本
        // String json2 = STR."""
        //     {
        //         "name": "\{name}",
        //         "age": \{age}
        //     }
        //     """;
    }
}

分代ZGC

bash
# 启用分代ZGC
java -XX:+UseZGC -XX:+ZGenerational MyApp

# 分代ZGC改进了性能,特别是对于年轻代对象的收集

Sequenced Collections

java
import java.util.SequencedCollection;
import java.util.SequencedSet;
import java.util.SequencedMap;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;

public class SequencedCollectionDemo {
    public static void main(String[] args) {
        // SequencedCollection
        SequencedCollection<String> list = new LinkedHashSet<>();
        list.add("A");
        list.add("B");
        list.add("C");
        
        System.out.println(list.getFirst());  // A
        System.out.println(list.getLast());   // C
        
        list.addFirst("X");  // 添加到开头
        list.addLast("Y");   // 添加到末尾
        
        list.removeFirst();
        list.removeLast();
        
        SequencedCollection<String> reversed = list.reversed();
        
        // SequencedMap
        SequencedMap<String, Integer> map = new LinkedHashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        
        System.out.println(map.firstEntry());  // A=1
        System.out.println(map.lastEntry());   // B=2
        
        SequencedMap<String, Integer> reversedMap = map.reversed();
    }
}

Java 18-21特性总结

版本重要特性
Java 18默认UTF-8编码、简单Web服务器、代码片段
Java 19虚拟线程预览、结构化并发预览
Java 20虚拟线程增强、记录模式预览
Java 21 LTS虚拟线程正式版、结构化并发、模式匹配增强、Sequenced Collections