JEP 437: Structured Concurrency ● スレッド間の同期にjoinやwaitを使うと実質的にはgo toに ● 管理が大変 try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Future user = scope.fork(() -> findUser()); Future order = scope.fork(() -> fetchOrder()); scope.join(); // Join both forks scope.throwIfFailed(); // ... and propagate errors // Here, both forks have succeeded, so compose their results return new Response(user.resultNow(), order.resultNow()); }
Sealed型 ● java.nio.Bufferのように継承を使う場合 ● コンストラクタをパッケージプライベートにすると限定できる ● javaパッケージであれば新たに追加されることはない ● アプリケーションクラスではJARをあとから追加が可能 ● 可能な型を限定できない ● sealed型で限定 sealed interface Type { record Bulk(int price, int unit) implements Type {} record Packed(int price) implements Type {} } sealed interface Type permits Bulk, Packed {} record Bulk(int price, int unit) implements Type {} record Packed(int price) implements Type {}
データの処理を考える ● こんな値を合計する record Product(String name, Type type) {} record Item(Product product, int amount) {} var cart = List.of( new Item(new Product("餃子", new Packed(300)), 3), new Item(new Product("牛肉", new Bulk(250, 100)), 230));
Switch式 ● Java 14で正式導入 int total = cart.stream() .mapToInt(item -> switch(item) { case Item(Product(var n, Packed(int price)), int amount) -> price * amount; case Item(Product(var n, Bulk(int price, int unit)), int amount) -> price * amount / unit; }).sum(); ※ バグを踏んだので、このコードはJava 20で動きません ※ 4月リリースのJava 20.0.1で動く