נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
37
חלקPart 6: Concurrency ו-ThreadsConcurrency & threads כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

CompletableFuture ו-virtual threadsCompletableFuture & virtual threads

שרשראות אסינכרוניות עם CompletableFuture, טיפול בשגיאות, ו-virtual threads של Java 21 לאלפי משימות.

Asynchronous chains with CompletableFuture, error handling, and Java 21 virtual threads for thousands of tasks.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • CompletableFuture: Future שאפשר לשרשר:CompletableFuture: A Future you can chain:
  • virtual thread: thread קל מאוד (Java 21) שה-JVM מנהל.virtual thread: A very light thread (Java 21) managed by the JVM.
  • supplyAsync מריץ את fetchTitle ב-thread אחר.supplyAsync runs fetchTitle on another thread.
  • כל thenApply רץ כשהשלב הקודם מסתיים.Each thenApply runs when the previous stage finishes.
  • thenCombine מחכה לשתי משימות ומחבר את התוצאות.thenCombine waits for two tasks and combines the results.
  • כשמשימה נכשלת, exceptionally נותן ערך חלופי במקום לזרוק.When a task fails, exceptionally gives a fallback value instead of throwing.
  • כל משימה ישנה 10ms.Each task sleeps 10ms.
  • עם 10,000 threads רגילים המחשב היה נאבק; עם virtual threads זה לוקח רגע.With 10,000 regular threads the computer would struggle; with virtual threads it takes a moment.
  • `java.util.concurrent.CompletionException:`java.util.concurrent.CompletionException:

מונחיםTerms

  • CompletableFutureCompletableFuture: Future שאפשר לשרשר: supplyAsync מתחיל משימה, thenApply ממיר את התוצאה, thenCombine מחבר שתיים, thenCompose משרשר משימה אסינכרונית נוספת, ו-join() מחכה.A Future you can chain: supplyAsync starts a task, thenApply transforms the result, thenCombine joins two, thenCompose chains another async task, and join() waits.
  • virtual threadvirtual thread: thread קל מאוד (Java 21) שה-JVM מנהל. כשהוא מחכה (sleep, רשת, קובץ) הוא לא תופס thread של מערכת ההפעלה, ולכן אפשר להריץ עשרות אלפים.A very light thread (Java 21) managed by the JVM. When it waits (sleep, network, a file) it doesn't hold an OS thread, so you can run tens of thousands.
  • אסינכרוניasynchronous: "תתחיל את זה, ותודיע לי כשיש תוצאה", במקום לחכות בשורה. שימושי כשרוב הזמן מחכים לרשת או לדיסק."Start this, and tell me when there's a result", instead of waiting in line. Useful when most of the time is spent waiting for the network or disk.
  • CompletableFutureCompletableFuture: Future שאפשר לשרשר: supplyAsync מתחיל משימה, thenApply ממיר את התוצאה, thenCombine מחבר שתיים, thenCompose משרשר משימה אסינכרונית נוספת, ו-join() מחכה.A Future you can chain: supplyAsync starts a task, thenApply transforms the result, thenCombine joins two, thenCompose chains another async task, and join() waits.
  • virtual threadvirtual thread: thread קל מאוד (Java 21) שה-JVM מנהל. כשהוא מחכה (sleep, רשת, קובץ) הוא לא תופס thread של מערכת ההפעלה, ולכן אפשר להריץ עשרות אלפים.A very light thread (Java 21) managed by the JVM. When it waits (sleep, network, a file) it doesn't hold an OS thread, so you can run tens of thousands.
  • אסינכרוניasynchronous: "תתחיל את זה, ותודיע לי כשיש תוצאה", במקום לחכות בשורה. שימושי כשרוב הזמן מחכים לרשת או לדיסק."Start this, and tell me when there's a result", instead of waiting in line. Useful when most of the time is spent waiting for the network or disk.

Cheatsheet

שרשרת של שלביםA chain of stages
CompletableFuture<String> title = CompletableFuture.supplyAsync(() -> fetchTitle(1))
        .thenApply(String::toUpperCase)
        .thenApply(t -> "Book: " + t);
System.out.println(title.join());
שילוב ושגיאותCombining and errors
CompletableFuture<Integer> pages = CompletableFuture.supplyAsync(() -> 412);
CompletableFuture<Double> rating = CompletableFuture.supplyAsync(() -> 4.5);
String summary = pages.thenCombine(rating, (p, r) -> p + " pages, rating " + r).join();
System.out.println(summary);
CompletableFuture<Integer> broken = CompletableFuture.supplyAsync(() -> Integer.parseInt("19x5"));
System.out.println(broken.exceptionally(e -> -1).join());
10,000 virtual threads10,000 virtual threads
AtomicInteger done = new AtomicInteger();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        ex.submit(() -> {
            Thread.sleep(10);
            return done.incrementAndGet();
        });
    }
}
System.out.println("finished " + done.get() + " tasks");

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
CompletionExceptionצייד באגים: שגיאה בשרשרתBug hunter: an error in the chainjava.util.concurrent.CompletionException: java.lang.NumberFormatException: For input string: "19x5": החריגה מהמשימה מגיעה עטופה ל-join.java.util.concurrent.CompletionException: java.lang.NumberFormatException: For input string: "19x5": the task's exception reaches join wrapped.

נבנה על ידיBuilt by Ariel Yohimovich