נבנה על ידי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.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • CompletableFuture: Future שאפשר לשרשר: supplyAsync מתחיל משימה, thenApply ממיר את התוצאה, thenCombine מחבר שתיים, thenCompose משרשר משימה אסינכרונית נוספת, ו-join() מחכה.CompletableFuture: 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 thread: thread קל מאוד (Java 21) שה-JVM מנהל. כשהוא מחכה (sleep, רשת, קובץ) הוא לא תופס thread של מערכת ההפעלה, ולכן אפשר להריץ עשרות אלפים.virtual 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.

02שרשרת של שלביםA chain of stages

supplyAsync מריץ את fetchTitle ב-thread אחר. כל thenApply רץ כשהשלב הקודם מסתיים. join() מחכה לסוף השרשרת.

supplyAsync runs fetchTitle on another thread. Each thenApply runs when the previous stage finishes. join() waits for the end of the chain.

Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    static String fetchTitle(int id) {
        return id == 1 ? "dune" : "emma";
    }

    public static void main(String[] args) {
        CompletableFuture<String> title = CompletableFuture.supplyAsync(() -> fetchTitle(1))
                .thenApply(String::toUpperCase)
                .thenApply(t -> "Book: " + t);
        System.out.println(title.join());
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
Book: DUNE

3 הרצות אמיתיות בזמן בניית האתר (JDK 21):3 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
Book: DUNE3
start ו-joinstart and join

03שילוב ושגיאותCombining and errors

thenCombine מחכה לשתי משימות ומחבר את התוצאות. כשמשימה נכשלת, exceptionally נותן ערך חלופי במקום לזרוק.

thenCombine waits for two tasks and combines the results. When a task fails, exceptionally gives a fallback value instead of throwing.

Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        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());
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
412 pages, rating 4.5
-1

3 הרצות אמיתיות בזמן בניית האתר (JDK 21):3 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
412 pages, rating 4.5 -13
start ו-joinstart and join

0410,000 virtual threads10,000 virtual threads

כל משימה ישנה 10ms. עם 10,000 threads רגילים המחשב היה נאבק; עם virtual threads זה לוקח רגע. ה-try סוגר את ה-executor ומחכה לכל המשימות.

Each task sleeps 10ms. With 10,000 regular threads the computer would struggle; with virtual threads it takes a moment. The try closes the executor and waits for every task.

Main.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        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");
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
finished 10000 tasks

3 הרצות אמיתיות בזמן בניית האתר (JDK 21):3 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
finished 10000 tasks3
מה קורה בתוך thread poolWhat happens inside a thread pool

05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: שגיאה בשרשרת

Bug hunter: an error in the chain

Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        int year = CompletableFuture.supplyAsync(() -> Integer.parseInt("19x5")).join();
        System.out.println("year " + year);
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.NumberFormatException: For input string: "19x5"
	at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:315)
	at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:320)
	at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1770)
	at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: java.lang.NumberFormatException: For input string: "19x5"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:778)
	at Main.lambda$main$0(Main.java:5)
	at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768)
	... 1 more
בעברית פשוטה: In plain words: java.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.

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

1000 שורות, כל ייבוא "מחכה לרשת" 20ms. משימה לכל שורה ב-newVirtualThreadPerTaskExecutor() (ב-try-with-resources). אספו Futures והדפיסו 1000 books imported, newest 1999. ברצף זה היה לוקח 20 שניות.

1000 lines, each import "waits for the network" 20ms. A task per line in newVirtualThreadPerTaskExecutor() (in try-with-resources). Collect Futures and print 1000 books imported, newest 1999. One by one it would take 20 seconds.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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