0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java 17から25への移行ガイド

Posted at

Java 17から25への移行ガイド

目次


Java 18の新機能

1. UTF-8がデフォルト文字セットに

// Java 17以前: 明示的に指定が必要だった
FileReader reader = new FileReader(file, StandardCharsets.UTF_8);

// Java 18以降: UTF-8がデフォルト
FileReader reader = new FileReader(file);

2. Simple Web Server

// 開発用の簡易HTTPサーバー
// コマンドライン: jwebserver -p 8080

Java 19の新機能

1. Record Patterns (Preview)

// Java 17
if (obj instanceof Point) {
    Point p = (Point) obj;
    int x = p.x();
    int y = p.y();
}

// Java 19以降
if (obj instanceof Point(int x, int y)) {
    System.out.println("x: " + x + ", y: " + y);
}

2. Virtual Threads (Preview)

// Java 17: 従来のスレッド
Thread thread = new Thread(() -> {
    System.out.println("Hello from thread");
});
thread.start();

// Java 19以降: Virtual Threads
Thread.startVirtualThread(() -> {
    System.out.println("Hello from virtual thread");
});

Java 20の新機能

1. Scoped Values (Incubator)

// スレッド間でイミュータブルなデータを共有
final static ScopedValue<String> USER = ScopedValue.newInstance();

ScopedValue.where(USER, "alice").run(() -> {
    System.out.println(USER.get()); // "alice"
});

2. Record Patterns (2nd Preview)

// ネストされたパターンマッチング
record Point(int x, int y) {}
record Rectangle(Point upperLeft, Point lowerRight) {}

if (obj instanceof Rectangle(Point(var x1, var y1), Point(var x2, var y2))) {
    System.out.println("Rectangle from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")");
}

Java 21の新機能 (LTS)

1. Virtual Threads (正式版)

// 大量の並行処理を軽量に実行
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i -> {
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1));
            return i;
        });
    });
}

2. Sequenced Collections

// Java 17: 最初と最後の要素へのアクセスが面倒
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
String first = list.get(0);
String last = list.get(list.size() - 1);

// Java 21以降: 直感的なAPI
SequencedCollection<String> list = new ArrayList<>(List.of("A", "B", "C"));
String first = list.getFirst();
String last = list.getLast();
list.addFirst("Z");
list.addLast("D");

3. Pattern Matching for switch (正式版)

// Java 17
String formatted;
if (obj instanceof Integer i) {
    formatted = String.format("int %d", i);
} else if (obj instanceof Long l) {
    formatted = String.format("long %d", l);
} else if (obj instanceof Double d) {
    formatted = String.format("double %f", d);
} else {
    formatted = obj.toString();
}

// Java 21以降
String formatted = switch (obj) {
    case Integer i -> String.format("int %d", i);
    case Long l    -> String.format("long %d", l);
    case Double d  -> String.format("double %f", d);
    case String s  -> String.format("String %s", s);
    default        -> obj.toString();
};

4. Record Patterns (正式版)

record Point(int x, int y) {}

// Java 17
if (obj instanceof Point) {
    Point p = (Point) obj;
    System.out.println(p.x() + p.y());
}

// Java 21以降
if (obj instanceof Point(int x, int y)) {
    System.out.println(x + y);
}

// switchとの組み合わせ
String result = switch (obj) {
    case Point(int x, int y) -> "Point: " + x + ", " + y;
    case null -> "null";
    default -> "Unknown";
};

5. String Templates (Preview)

// Java 17
String name = "Alice";
int age = 30;
String message = "Hello, " + name + "! You are " + age + " years old.";

// Java 21以降 (Preview)
String message = STR."Hello, \{name}! You are \{age} years old.";

Java 22の新機能

1. Unnamed Variables & Patterns

// Java 21以前: 使わない変数でも名前が必要
try {
    // ...
} catch (Exception e) {
    // eを使わない場合でも書く必要があった
}

// Java 22以降: アンダースコアで省略可能
try {
    // ...
} catch (Exception _) {
    System.out.println("Error occurred");
}

// パターンマッチングでも使用可能
if (obj instanceof Point(int x, int _)) {
    // y座標は無視
    System.out.println("x: " + x);
}

2. Statements before super()

// Java 21以前: super()の前に処理を書けなかった
class Child extends Parent {
    Child(String value) {
        // ここに処理を書けなかった
        super(value);
    }
}

// Java 22以降: super()の前に処理を書ける
class Child extends Parent {
    Child(String value) {
        String processed = value.toUpperCase(); // OK
        super(processed);
    }
}

3. Foreign Function & Memory API (正式版)

// Cライブラリなどのネイティブコードを呼び出し
try (Arena arena = Arena.ofConfined()) {
    MemorySegment segment = arena.allocate(100);
    segment.setAtIndex(ValueLayout.JAVA_INT, 0, 42);
}

Java 23の新機能

1. Primitive Types in Patterns

// プリミティブ型のパターンマッチング
Object obj = 42;

// Java 22以前: ラッパークラスのみ
if (obj instanceof Integer i) {
    int value = i;
}

// Java 23以降: プリミティブ型も直接
if (obj instanceof int i) {
    System.out.println(i * 2);
}

2. Module Import Declarations (Preview)

// Java 22以前: 個別にインポート
import java.util.List;
import java.util.Map;
import java.util.Set;

// Java 23以降: モジュール全体をインポート
import module java.base;

3. Markdown Documentation Comments (Preview)

// Java 22以前: HTML形式のJavadoc
/**
 * This is a <b>bold</b> text.
 * <p>
 * Example:
 * <pre>
 * {@code
 * var list = new ArrayList<>();
 * }
 * </pre>
 */

// Java 23以降: Markdown形式
/// This is a **bold** text.
///
/// Example:
/// ```java
/// var list = new ArrayList<>();
/// ```

Java 24の新機能

1. Flexible Constructor Bodies (2nd Preview)

// コンストラクタでより柔軟な初期化が可能
class DataProcessor {
    private final String data;
    
    DataProcessor(String input) {
        // 検証ロジック
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException();
        }
        // 前処理
        String processed = input.trim().toLowerCase();
        // super()やthis()の前に処理可能
        super();
        this.data = processed;
    }
}

2. Stream Gatherers

// カスタムストリーム中間操作
List<Integer> numbers = List.of(1, 2, 3, 4, 5);

// 独自のカスタム処理
var result = numbers.stream()
    .gather(customGatherer())
    .toList();

Java 25の新機能

1. Primitive Types in Patterns (正式版予定)

// パターンマッチングでプリミティブ型を直接使用
Object value = 100;

String result = switch(value) {
    case int i when i > 0 -> "Positive: " + i;
    case int i when i < 0 -> "Negative: " + i;
    case int i -> "Zero";
    default -> "Not an integer";
};

2. Enhanced Collection Literals

// コレクションリテラルの改善(提案段階)
// より簡潔な記法が可能になる見込み
List<String> list = ["apple", "banana", "cherry"];
Set<Integer> set = {1, 2, 3};
Map<String, Integer> map = {"one": 1, "two": 2};

移行時の注意点

1. パフォーマンスへの影響

  • Virtual Threadsは従来のスレッドプールと使い分けが必要
  • CPU集約的なタスクには従来のスレッドプールが適している

2. 後方互換性

  • Java 21 (LTS)への移行を推奨
  • Preview機能は本番環境では使用を控える

3. ビルドツールの対応確認

<!-- Maven: pom.xml -->
<properties>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
</properties>
// Gradle: build.gradle
java {
    sourceCompatibility = JavaVersion.VERSION_21
    targetCompatibility = JavaVersion.VERSION_21
}

4. 廃止されたAPI

  • 一部の古いAPIが削除される可能性があるため、事前確認が必要
  • SecurityManagerはJava 17で非推奨、将来的に削除予定

実務での活用例

Virtual Threadsを使った並行処理

// 従来の方法(Java 17)
ExecutorService executor = Executors.newFixedThreadPool(100);
for (int i = 0; i < 10000; i++) {
    final int taskId = i;
    executor.submit(() -> processTask(taskId));
}
executor.shutdown();

// Virtual Threads(Java 21以降)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10000; i++) {
        final int taskId = i;
        executor.submit(() -> processTask(taskId));
    }
} // 自動的にクローズされる

Sequenced Collectionsを使ったコード簡略化

// Java 17
List<String> items = new ArrayList<>();
items.add("First");
items.add("Second");
items.add(0, "NewFirst"); // 先頭に追加
String last = items.remove(items.size() - 1); // 末尾を削除

// Java 21
List<String> items = new ArrayList<>();
items.addFirst("First");
items.addLast("Second");
items.addFirst("NewFirst");
String last = items.removeLast();

Pattern Matchingを使った型安全なコード

// Java 17
public double calculateArea(Shape shape) {
    if (shape instanceof Circle) {
        Circle circle = (Circle) shape;
        return Math.PI * circle.radius() * circle.radius();
    } else if (shape instanceof Rectangle) {
        Rectangle rect = (Rectangle) shape;
        return rect.width() * rect.height();
    } else {
        throw new IllegalArgumentException();
    }
}

// Java 21
public double calculateArea(Shape shape) {
    return switch (shape) {
        case Circle(double radius) -> Math.PI * radius * radius;
        case Rectangle(double width, double height) -> width * height;
        default -> throw new IllegalArgumentException();
    };
}

まとめ

重要な変更点トップ5

  1. Virtual Threads (Java 21) - 並行処理の革新
  2. Pattern Matching for switch (Java 21) - コードの簡潔化
  3. Sequenced Collections (Java 21) - コレクションAPIの改善
  4. Record Patterns (Java 21) - パターンマッチングの強化
  5. Unnamed Variables (Java 22) - 不要な変数の省略

推奨される移行パス

  1. まずJava 21 (LTS)への移行を優先
  2. 既存コードの動作確認
  3. 新機能の段階的な導入
  4. Preview機能は実験的に使用し、正式版を待つ

最終更新: 2024年
対象バージョン: Java 17 → Java 25

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?