$30 off During Our Annual Pro Sale. View Details »

Java 18新機能とJava 19以降に入りそうな機能

Java 18新機能とJava 19以降に入りそうな機能

2022/3/29に行われたJJUG ナイトセミナーでの登壇資料です
https://jjug.doorkeeper.jp/events/134652

Naoki Kishida

March 29, 2022
Tweet

More Decks by Naoki Kishida

Other Decks in Programming

Transcript

  1. Java 18の概要とツール・言語の新機能
    Java 19以降に盛り込まれそうなJEPの紹介
    2022/3/29 JJUGナイトセミナー
    LINE Fukuoka きしだ なおき

    View Slide

  2. 自己紹介
    • きしだ なおき
    • LINE Fukuoka
    • Developer Relations
    • twitter: @kis

    View Slide

  3. プロになるJava

    プロになるのだ! with @yusuke, @zinbe

    Javaでプログラミングの勉強をする本
    – Not 「Javaの勉強をする本」

    etc. floatやlongは扱ってない

    全部入り
    – Java 17, JShell, Maven, JUnit, Spring Boot, アルゴリズム, プロトコル
    – 目次みて「だいたい知ってる内容かな?」と思った人に読んで欲しい

    あと、オブジェクト指向をdisる本です
    – オブジェクト指向が、いかに現代のJavaで使えないか書いてます
    – (この話すると3日くらいかかるので略。プロJavaのP337読んで)

    View Slide

  4. Java 18の概要とツール・言語の新機能

    View Slide

  5. Java 18

    2022/3/22 released

    non-LTS

    9 JEPs
    http://jdk.java.net/18/

    View Slide

  6. 用語

    JEP(JDK Enhancement Proposal)
    – 機能改善のまとめ
    – Javaの主な仕様変更はJEPとしてまとめられている

    LTS(Long Term Support)
    – 長期サポート
    – 6バージョンごとにLTSが設定されて長期間のサポートが行われる。
    – 現在のLTSは17で、次回は23(21をLTSにしようという話も)
    – 18はLTSではないので19が出ればバグ修正などは行われなくなる。

    View Slide

  7. 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)

    View Slide

  8. 試用機能

    大きな新機能について試用版として導入するこ
    とでフィードバックを得やすくしてよりよい機
    能を提供できるようにする
    – 言語機能:Preview
    – API:Incubator
    – JVM機能:Experimental

    View Slide

  9. 資料

    JDK 18 Release Notes
    – https://jdk.java.net/18/release-notes

    Java 18新機能まとめ
    – https://qiita.com/nowokay/items/17d990aa8a5b1c5223c8

    View Slide

  10. Java 18 ディストリビューション

    Oracle OpenJDK

    Oracle JDK

    Amazon Corretto 18

    Liberica JDK

    Azul Zulu

    Sap Machine

    View Slide

  11. ツール

    UTF-8 by Default

    Simple Web Server

    Code Snippets in Java API Documentation

    View Slide

  12. 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サーバーを使ってる人は注意

    View Slide

  13. 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()

    View Slide

  14. 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());
    * }
    * }
    */

    View Slide

  15. 言語

    Pattern Matching for switch(2nd preview)

    View Slide

  16. 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();
    }

    View Slide

  17. 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になる模様

    View Slide

  18. `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: ...

    View Slide

  19. `default` in `case`

    `defualt`を`case`に
    jshell> switch (s) {
    ...> case "one" -> 1;
    ...> case "two" -> 2;
    ...> case null, default -> -1;
    ...> }
    $21 ==> -1

    View Slide


  20. 小変更

    Reimplement Core Reflection with Method
    Handles

    Internet-Address Resolution SPI

    Foreign Function & Memory API

    Vector API
    API

    View Slide

  21. 小変更

    Math / StrictMath
    – ceilDiv, ceilMod
    – divideExact, floorDivExact

    Throw exception
    – unsignedMultiplyHigh

    Duration
    – IsPositive

    HttpRequest.Builder.HEAD

    View Slide

  22. Java 19以降に盛り込まれそうなJEPの紹介

    View Slide

  23. Java 19以降に入りそうなJEP

    Project Amber
    – String Templates
    – Pattern Matching improvement

    Project Valhalla
    – Value Object
    – Primitive Class
    – Universal Generics

    Project Loom
    – Virtual Threads

    View Slide

  24. 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

    View Slide

  25. 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);
    };
    }

    View Slide

  26. Project Valhalla

    Value Objects

    Primitive Class

    Universal Generics

    View Slide

  27. 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[] array;
    int offset;

    View Slide

  28. 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;

    View Slide

  29. Identity Class

    既存のクラス

    View Slide

  30. 違いは?
    Identity Null Immutable 継承 atomic ロック
    Identity Class Yes Yes No 可 yes
    (初期化)

    Value Class No Yes Yes 不可 yes 不可
    Primitive Class No No Yes 不可 no 不可
    Value Classを基本に考えるのがよさそう

    View Slide

  31. Draft: Universal Generics

    ジェネリクスにprimitiveが使える
    – `List`
    http://openjdk.java.net/jeps/8261529

    View Slide

  32. Project Loom

    Virtual Thread

    Structured Thread

    Scope Local

    View Slide

  33. 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()

    View Slide

  34. Draft: Structured Concurrency

    スレッドの関係を定義することができなかった
    – barかbazがエラーで止まったら片方も止めたい
    – bar/bazが実行中にfooのスレッドダンプをとったら
    bar/bazの状況も見たい
    String foo() throws IOException, InterruptedException {
    Future bar = myExecutorService.submit(() -> bar());
    Future 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

    View Slide

  35. Scope Local

    ThreadLocalのもっと細かいの

    setメソッドを持たない
    static final ScopeLocal x = ScopeLocal.newInstance();
    static final ScopeLocal 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

    View Slide

  36. 先が楽しみ

    地味なリリース

    けれども着実に進化している
    – 大きな機能改善への準備

    View Slide