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

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

שרשרת של ניקויA cleaning chain

תזכורת: מה ביקשוReminder: the task

מתחילים עם " ulysses " ב-supplyAsync, ואז שלושה thenApply: trim, אות ראשונה גדולה, והוספת האורך. הדפיסו Ulysses (7).

Start with " ulysses " in supplyAsync, then three thenApplys: trim, a capital first letter, and adding the length. Print Ulysses (7).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        String result = CompletableFuture.supplyAsync(() -> "  ulysses ")
                .thenApply(String::trim)
                .thenApply(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
                .thenApply(s -> s + " (" + s.length() + ")")
                .join();
        System.out.println(result);
    }
}
פלטOutput
Ulysses (7)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

שני מקורות, תוצאה אחתTwo sources, one result

תזכורת: מה ביקשוReminder: the task

שתי משימות במקביל: מספר עמודים (474) ודירוג (4.0). חברו עם thenCombine והדפיסו 474 pages, rating 4.0.

Two tasks in parallel: a page count (474) and a rating (4.0). Combine with thenCombine and print 474 pages, rating 4.0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        CompletableFuture<Integer> pages = CompletableFuture.supplyAsync(() -> 474);
        CompletableFuture<Double> rating = CompletableFuture.supplyAsync(() -> 4.0);
        String summary = pages.thenCombine(rating, (p, r) -> p + " pages, rating " + r).join();
        System.out.println(summary);
    }
}
פלטOutput
474 pages, rating 4.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

צייד באגים: שגיאה בשרשרתBug hunter: an error in the chain

תזכורת: מה ביקשוReminder: the task

join() זורק כי ההמרה נכשלה. הוסיפו exceptionally(e -> 0) לפני ה-join כך שיודפס year 0.

join() throws because the conversion failed. Add exceptionally(e -> 0) before the join so it prints year 0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        int year = CompletableFuture.supplyAsync(() -> Integer.parseInt("19x5"))
                .exceptionally(e -> 0)
                .join();
        System.out.println("year " + year);
    }
}
פלטOutput
year 0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

allOfallOf

תזכורת: מה ביקשוReminder: the task

לכל כותר משימה שמחשבת עמודים (אורך × 100). חכו לכולן עם CompletableFuture.allOf(...), ואז סכמו: total pages 1500.

A task per title computing pages (length × 100). Wait for them all with CompletableFuture.allOf(...), then sum: total pages 1500.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Main {
    static int pages(String title) {
        return title.length() * 100;
    }

    public static void main(String[] args) {
        List<String> titles = List.of("Dune", "Emma", "Ulysses");
        List<CompletableFuture<Integer>> all = titles.stream()
                .map(t -> CompletableFuture.supplyAsync(() -> pages(t)))
                .toList();
        CompletableFuture.allOf(all.toArray(new CompletableFuture[0])).join();
        int total = all.stream().mapToInt(CompletableFuture::join).sum();
        System.out.println("total pages " + total);
    }
}
פלטOutput
total pages 1500

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 37: ייבוא עם virtual threadsShelf, step 37: import with virtual threads

תזכורת: מה ביקשוReminder: the task

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.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    record Book(String title, int year) {
    }

    static Book importLine(String line) throws InterruptedException {
        Thread.sleep(20);
        String[] f = line.split(";");
        return new Book(f[0], Integer.parseInt(f[1]));
    }

    public static void main(String[] args) throws Exception {
        List<String> lines = new ArrayList<>();
        for (int i = 1; i <= 1000; i++) {
            lines.add("Book " + i + ";" + (1900 + i % 100));
        }
        List<Future<Book>> futures = new ArrayList<>();
        try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
            for (String l : lines) {
                futures.add(ex.submit(() -> importLine(l)));
            }
        }
        int newest = 0;
        for (Future<Book> f : futures) {
            newest = Math.max(newest, f.get().year());
        }
        System.out.println(futures.size() + " books imported, newest " + newest);
    }
}
פלטOutput
1000 books imported, newest 1999

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

thenComposethenCompose

תזכורת: מה ביקשוReminder: the task

findId(title) ו-loadAuthor(id) מחזירות שתיהן CompletableFuture. שרשרו עם thenCompose (לא thenApply) והדפיסו Herbert עבור Dune.

findId(title) and loadAuthor(id) both return a CompletableFuture. Chain them with thenCompose (not thenApply) and print Herbert for Dune.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    static CompletableFuture<Integer> findId(String title) {
        return CompletableFuture.supplyAsync(() -> title.length());
    }

    static CompletableFuture<String> loadAuthor(int id) {
        return CompletableFuture.supplyAsync(() -> id == 4 ? "Herbert" : "unknown");
    }

    public static void main(String[] args) {
        String author = findId("Dune").thenCompose(Main::loadAuthor).join();
        System.out.println(author);
    }
}
פלטOutput
Herbert

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

וירטואלי מול רגילVirtual vs platform

תזכורת: מה ביקשוReminder: the task

צרו thread וירטואלי עם Thread.ofVirtual().start(...) ו-thread רגיל עם Thread.ofPlatform().start(...). כל אחד מדפיס isVirtual(): virtual? true ואז virtual? false.

Create a virtual thread with Thread.ofVirtual().start(...) and a platform thread with Thread.ofPlatform().start(...). Each prints isVirtual(): virtual? true then virtual? false.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs

כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.

With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread v = Thread.ofVirtual().name("reader").start(() -> System.out.println("virtual? " + Thread.currentThread().isVirtual()));
        v.join();
        Thread p = Thread.ofPlatform().name("writer").start(() -> System.out.println("virtual? " + Thread.currentThread().isVirtual()));
        p.join();
    }
}
פלטOutput
virtual? true
virtual? false

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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