Share
Embed
Java 18新機能とJava 19以降に入りそうな機能
2022/3/29に行われたJJUG ナイトセミナーでの登壇資料です
https://jjug.doorkeeper.jp/events/134652
Naoki Kishida
March 29, 2022
Transcript
36 slides
-
自己紹介 • きしだ なおき • LINE Fukuoka • Developer Relations
• twitter: @kis -
プロになるJava • プロになるのだ! with @yusuke, @zinbe • Javaでプログラミングの勉強をする本 – Not
「Javaの勉強をする本」 • etc. floatやlongは扱ってない • 全部入り – Java 17, JShell, Maven, JUnit, Spring Boot, アルゴリズム, プロトコル – 目次みて「だいたい知ってる内容かな?」と思った人に読んで欲しい • あと、オブジェクト指向をdisる本です – オブジェクト指向が、いかに現代のJavaで使えないか書いてます – (この話すると3日くらいかかるので略。プロJavaのP337読んで) -
Java 18 • 2022/3/22 released • non-LTS • 9 JEPs
http://jdk.java.net/18/ -
用語 • JEP(JDK Enhancement Proposal) – 機能改善のまとめ – Javaの主な仕様変更はJEPとしてまとめられている •
LTS(Long Term Support) – 長期サポート – 6バージョンごとにLTSが設定されて長期間のサポートが行われる。 – 現在のLTSは17で、次回は23(21をLTSにしようという話も) – 18はLTSではないので19が出ればバグ修正などは行われなくなる。 -
JEP • 言語 – JEP 420: Pattern Matching for switch
(Second Preview) • ツール – JEP 400: UTF-8 by Default – JEP 408: Simple Web Server – JEP 413: Code Snippets in Java API Documentation • 非推奨 – JEP 421: Deprecate Finalization for Removal • API – JEP 416: Reimplement Core Reflection with Method Handles – JEP 418: Internet-Address Resolution SPI – Incubators • JEP 417: Vector API (Third Incubator) • JEP 419: Foreign Function & Memory API (Second Incubator) -
資料 • JDK 18 Release Notes – https://jdk.java.net/18/release-notes • Java
18新機能まとめ – https://qiita.com/nowokay/items/17d990aa8a5b1c5223c8 -
Java 18 ディストリビューション • Oracle OpenJDK • Oracle JDK •
Amazon Corretto 18 • Liberica JDK • Azul Zulu • Sap Machine -
ツール • UTF-8 by Default • Simple Web Server •
Code Snippets in Java API Documentation -
UTF-8 by Default • UTF-8が標準APIのデフォルトcharsetに – file.encoding=UTF-8 • -Dfile.encoding=COMPAT –
Java 17と同様にシステムのcharsetをデフォルトに – native.encodingをfile.encodingに使う – native.encodingはJDK 17で導入されている • Windowsサーバーを使ってる人は注意 -
Simple Web Server • 静的ファイルを配信するSimple Web Server • テスト用(公開用には使わないほうがいい) •
jwebserver • API jshell> var server = SimpleFileServer.createFileServer(new InetSocketAddress(8000), Path.of("c:/Users/naoki"), OutputLevel.VERBOSE) server ==> sun.net.httpserver.HttpServerImpl@2f7c7260 jshell> server.start() -
Code Snippets in Java API Documentation • Javadocにコードスニペットを • 強調表示ができたり別ファイルのコード断片を
埋め込めたり便利 /** * The following code shows how to use {@code Optional.isPresent}: * {@snippet : * if (v.isPresent()) { * System.out.println("v: " + v.get()); * } * } */ -
Pattern Matching for switch • swichでパターンマッチ, ガード節 – Preview feature
• java/javac/jshellコマンドに`--preview-feature`が必要 Object o; System.out.println(switch (o) { case String s && s.length() >= 5 -> s.toUpperCase(); case String s -> " %s ".formatted(s); case Integer i -> "%,d".formatted(i); default -> o.toString(); } -
Pattern Matching for switch • swichでパターンマッチ, ガード節 – Preview feature
• java/javac/jshellコマンドに`--preview-feature`が必要 Object o; System.out.println(switch (o) { case String s when s.length() >= 5 -> s.toUpperCase(); case String s -> " %s ".formatted(s); case Integer i -> "%,d".formatted(i); default -> o.toString(); } ガード節はJava 19でwhenになる模様 -
`null` in `case` • `null`を`case`に使える • `null`caseがないときは, nullが来たらNPE jshell> String
s = null s ==> null jshell> switch (s) { ...> case "test" -> "テスト"; ...> case null -> "ぬるぽ"; ...> default -> "hello"; ...> } $13 ==> "ぬるぽ" jshell> switch (s) { ...> case "test" -> "テスト"; ...> default -> "hello"; ...> } | 例外 java.lang.NullPointerException: ... -
`default` in `case` • `defualt`を`case`に jshell> switch (s) { ...>
case "one" -> 1; ...> case "two" -> 2; ...> case null, default -> -1; ...> } $21 ==> -1 -
• 小変更 • Reimplement Core Reflection with Method Handles •
Internet-Address Resolution SPI • Foreign Function & Memory API • Vector API API -
小変更 • Math / StrictMath – ceilDiv, ceilMod – divideExact,
floorDivExact • Throw exception – unsignedMultiplyHigh • Duration – IsPositive • HttpRequest.Builder.HEAD -
Java 19以降に入りそうなJEP • Project Amber – String Templates – Pattern
Matching improvement • Project Valhalla – Value Object – Primitive Class – Universal Generics • Project Loom – Virtual Threads -
Draft: String Templates • 文字列リテラルへの式の埋め込み • いまの書き方 – 連結 –
String.format • String template – Simple – SQL injection? • Custom templating x + " plus " + y + " equals " + (x + y) String.format("%2$d plus %1$d equals %3$d", x, y, x + y) STR."\{x} + \{y} = \{x + y}" query."SELECT * FROM Person p WHERE p.last_name = \{name}" http://openjdk.java.net/jeps/8273943 -
Pattern Matchingの改善 • JEP 405: Record pattern – Java 19でプレビューとして入りそう
– レコードのDeconstruction(解体、脱構築) http://openjdk.java.net/jeps/405 int eval(Expr n) { return switch(n) { case IntExpr(int i) -> i; case NegExpr(Expr n) -> -eval(n); case AddExpr(Expr left, Expr right) -> eval(left) + eval(right); case MulExpr(Expr left, Expr right) -> eval(left) * eval(right); default -> throw new IllegalArgumentException(n); }; } -
Draft: Value Objects • Identityを持たないオブジェクト – Identityを持つ場合、値が同じでも別扱い • Immutable –
すべてfinal • 最適化をかけやすい。 – 平坦化、コピー • recordはIdentityを持つ – value record http://openjdk.java.net/jeps/8277163 value record NameAndScore(String name, int score) { } value class ArrayCursor<T> { T[] array; int offset; -
Primitive Class • JEP 401 Primitive Class – 新しい基本型が定義できるようになる •
JEP 402 Classes for the Basic Primitives – 既存の基本型のクラス定義 – `23.compareTo(34)`と書ける primitive class Point implements Shape { private double x; private double y; -
違いは? Identity Null Immutable 継承 atomic ロック Identity Class Yes
Yes No 可 yes (初期化) 可 Value Class No Yes Yes 不可 yes 不可 Primitive Class No No Yes 不可 no 不可 Value Classを基本に考えるのがよさそう -
Draft:Virtual Thread • JVM管理のスレッド(Green thread) – java.lang.ThreadはOS管理(Blue thread) • Lightweight
– OS管理のスレッドはなんでもできる – 結局通信空き時間にCPU使いたいだけ – OS管理のスレッドでリクエストさばくと大変 – Rxという地獄・・・ – そこでVirtual Thread http://openjdk.java.net/jeps/8277131 Executors.newVirtualThreadPerTaskExecutor() -
Draft: Structured Concurrency • スレッドの関係を定義することができなかった – barかbazがエラーで止まったら片方も止めたい – bar/bazが実行中にfooのスレッドダンプをとったら bar/bazの状況も見たい
String foo() throws IOException, InterruptedException { Future<Integer> bar = myExecutorService.submit(() -> bar()); Future<String> baz = myExecutorService.submit(() -> baz()); try { return baz.get() + bar.get(); } catch (ExecutionException e) { if (e.getCause() instanceof IOException ioe) throw ioe; throw new RuntimeException(e); } } http://openjdk.java.net/jeps/8277129 -
Scope Local • ThreadLocalのもっと細かいの • setメソッドを持たない static final ScopeLocal<MyType> x
= ScopeLocal.newInstance(); static final ScopeLocal<MyType> y = ScopeLocal.newInstance(); { ScopeLocal.where(x, expr1) .where(y, expr2) .run(() -> ... code that uses x.get() and y.get() ...); } http://openjdk.java.net/jeps/8263012