Java versions
versions6Java21Features
- Path
- pkg2versions/versions6Java21Features.java
- Package
- pkg2versions
- Study order
- 6
- Run
- Single-file source launch
- Command
- java pkg2versions/versions6Java21Features.java
- Version in the filename
- Java 21
- Example
- Java 21 example
- Requires
- Java 21
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg2versions;2 3/*4 * versions6Java21Features.java (2023, LTS) -- the target version for this project5 * ----------------------------------------------------------------------6 * FEATURES & WHY:7 * - Virtual Threads (JEP 444) : cheap threads for massive concurrent blocking I/O.8 * - Pattern matching for switch : exhaustive, type-based branching (final).9 * - Record patterns (JEP 440) : deconstruct records in switch/instanceof.10 * - Sequenced collections (JEP 431): getFirst/getLast/reversed on ordered collections.11 * - String templates, structured concurrency, and scoped values were previews12 * (not shown here). This file requires Java 21. It is not a Java 19 program.13 */14import java.util.*;15 16public class versions6Java21Features {17 18 sealed interface Shape permits Circle, Rect {}19 record Circle(double r) implements Shape {}20 record Rect(double w, double h) implements Shape {}21 22 static String describe(Object o) {23 // Record patterns + guards + exhaustive switch24 return switch (o) {25 case Circle(double r) when r > 10 -> "big circle r=" + r;26 case Circle(double r) -> "circle r=" + r;27 case Rect(double w, double h) -> "rect " + w + "x" + h;28 case null -> "null";29 default -> "other";30 };31 }32 33 public static void main(String[] args) throws InterruptedException {34 // Record patterns35 System.out.println(describe(new Circle(3)));36 System.out.println(describe(new Circle(20)));37 System.out.println(describe(new Rect(2, 5)));38 System.out.println(describe(null));39 40 // Sequenced collections (Java 21)41 SequencedCollection<Integer> seq = new ArrayList<>(List.of(1, 2, 3, 4));42 System.out.println("first=" + seq.getFirst() + " last=" + seq.getLast());43 System.out.println("reversed=" + seq.reversed());44 45 LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();46 lhm.put("a", 1); lhm.put("b", 2); lhm.put("c", 3);47 System.out.println("firstEntry=" + lhm.firstEntry() + " lastEntry=" + lhm.lastEntry());48 49 // Virtual threads: launch many cheap threads50 long start = System.currentTimeMillis();51 List<Thread> threads = new ArrayList<>();52 for (int i = 0; i < 1000; i++) {53 int id = i;54 Thread t = Thread.ofVirtual().start(() -> {55 try { Thread.sleep(10); } catch (InterruptedException ignored) {}56 });57 threads.add(t);58 }59 for (Thread t : threads) t.join();60 System.out.println("1000 virtual threads finished in " + (System.currentTimeMillis() - start) + "ms");61 }62}