נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
CompletableFuture ו-virtual threadsCompletableFuture & virtual threads
מפגש 37: שרשראות אסינכרוניות עם CompletableFuture, טיפול בשגיאות, ו-virtual threads של Java 21 לאלפי משימות.Session 37: Asynchronous chains with CompletableFuture, error handling, and Java 21 virtual threads for thousands of tasks.
שרשראות אסינכרוניות עם CompletableFuture, טיפול בשגיאות, ו-virtual threads של Java 21 לאלפי משימות. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Asynchronous chains with CompletableFuture, error handling, and Java 21 virtual threads for thousands of tasks. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- שרשרת של שלביםA chain of stages
- שילוב ושגיאותCombining and errors
- 10,000 virtual threads10,000 virtual threads
- טעויות נפוצותCommon mistakes
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- 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.
- אסינכרוני: "תתחיל את זה, ותודיע לי כשיש תוצאה", במקום לחכות בשורה.asynchronous: "Start this, and tell me when there's a result", instead of waiting in line.
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
שרשרת של שלביםA chain of stages
שרשרת של שלביםA chain of stages
supplyAsync מריץ את fetchTitle ב-thread אחר.supplyAsync runs fetchTitle on another thread.- כל
thenApply רץ כשהשלב הקודם מסתיים.Each thenApply runs when the previous stage finishes. join() מחכה לסוף השרשרת.join() waits for the end of the chain.
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.נושאTopic 3
שילוב ושגיאותCombining and errors
שילוב ושגיאותCombining and errors
thenCombine מחכה לשתי משימות ומחבר את התוצאות.thenCombine waits for two tasks and combines the results.- כשמשימה נכשלת,
exceptionally נותן ערך חלופי במקום לזרוק.When a task fails, exceptionally gives a fallback value instead of throwing.
thenCombine מחכה לשתי משימות ומחבר את התוצאות. כשמשימה נכשלת, exceptionally נותן ערך חלופי במקום לזרוק.thenCombine waits for two tasks and combines the results. When a task fails, exceptionally gives a fallback value instead of throwing.נושאTopic 4
10,000 virtual threads10,000 virtual threads
10,000 virtual threads10,000 virtual threads
- כל משימה ישנה 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.
- ה-
try סוגר את ה-executor ומחכה לכל המשימות.The try closes the executor and waits for every task.
כל משימה ישנה 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.נושאTopic 5
טעויות נפוצותCommon mistakes
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
- `java.util.concurrent.CompletionException:`java.util.concurrent.CompletionException:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.נושאTopic 6
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 37: ייבוא עם virtual threadsShelf, step 37: import with virtual threads
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.CompletableFuture: Future שאפשר לשרשר:CompletableFuture: A Future you can chain:
המונחים של המפגשThis session's termsvirtual thread: thread קל מאוד (Java 21) שה-JVM מנהל.virtual thread: A very light thread (Java 21) managed by the JVM.
המונחים של המפגשThis session's termsאסינכרוני: "תתחיל את זה, ותודיע לי כשיש תוצאה", במקום לחכות בשורה.asynchronous: "Start this, and tell me when there's a result", instead of waiting in line.
המונחים של המפגשThis session's termssupplyAsync מריץ את fetchTitle ב-thread אחר.supplyAsync runs fetchTitle on another thread.
שרשרת של שלביםA chain of stagesכל thenApply רץ כשהשלב הקודם מסתיים.Each thenApply runs when the previous stage finishes.
שרשרת של שלביםA chain of stagesjoin() מחכה לסוף השרשרת.join() waits for the end of the chain.
שרשרת של שלביםA chain of stagesthenCombine מחכה לשתי משימות ומחבר את התוצאות.thenCombine waits for two tasks and combines the results.
שילוב ושגיאותCombining and errorsכשמשימה נכשלת, exceptionally נותן ערך חלופי במקום לזרוק.When a task fails, exceptionally gives a fallback value instead of throwing.
שילוב ושגיאותCombining and errorsכל משימה ישנה 10ms.Each task sleeps 10ms.
10,000 virtual threads10,000 virtual threadsעם 10,000 threads רגילים המחשב היה נאבק; עם virtual threads זה לוקח רגע.With 10,000 regular threads the computer would struggle; with virtual threads it takes a moment.
10,000 virtual threads10,000 virtual threadsה-try סוגר את ה-executor ומחכה לכל המשימות.The try closes the executor and waits for every task.
10,000 virtual threads10,000 virtual threads`java.util.concurrent.CompletionException:`java.util.concurrent.CompletionException:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמדף, צעד 37: ייבוא עם virtual threadsShelf, step 37: import with virtual threads
הצעד של היום בפרויקט מדףToday's step in the Shelf projectמה ההבדל בין thenApply ל-thenCompose?What's the difference between thenApply and thenCompose?
thenCompose משרשר פונקציה שמחזירה בעצמה CompletableFuturethenCompose chains a function that itself returns a CompletableFuture- אין הבדלNone
thenApply אסינכרוני ו-thenCompose לאthenApply is async and thenCompose isn'tthenCompose מטפל בשגיאותthenCompose handles errors
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.thenCompose משרשר פונקציה שמחזירה בעצמה CompletableFuturethenCompose chains a function that itself returns a CompletableFuture
נכון, בלי לקבל CompletableFuture בתוך CompletableFuture.Right, without getting a CompletableFuture inside a CompletableFuture.מתי virtual threads עוזרים במיוחד?When do virtual threads help most?
- כשהמשימות מחכות הרבה (רשת, קבצים, sleep)When tasks wait a lot (network, files, sleep)
- בחישובים כבדים על המעבדIn heavy CPU calculations
- אף פעםNever
- רק ב-SwingOnly in Swing
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כשהמשימות מחכות הרבה (רשת, קבצים, sleep)When tasks wait a lot (network, files, sleep)
נכון.Right.משימה ב-supplyAsync זרקה חריגה. מה exceptionally(e -> 0) נותן?A task in supplyAsync threw. What does exceptionally(e -> 0) give?
- 0 במקום החריגה0 instead of the exception
- את החריגהThe exception
- nullnull
- מריץ שובRuns again
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.0 במקום החריגה0 instead of the exception
נכון.Right.שרשרת של ניקויA cleaning chain
- מתחילים עם
" ulysses " ב-supplyAsync, ואז שלושה thenApply:Start with " ulysses " in supplyAsync, then three thenApplys:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.שני מקורות, תוצאה אחתTwo sources, one result
- שתי משימות במקביל:Two tasks in parallel:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: שגיאה בשרשרתBug hunter: an error in the chain
join() זורק כי ההמרה נכשלה.join() throws because the conversion failed.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.allOfallOf
- לכל כותר משימה שמחשבת עמודים (אורך × 100).A task per title computing pages (length × 100).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 37: ייבוא עם virtual threadsShelf, step 37: import with virtual threads
- 1000 שורות, כל ייבוא "מחכה לרשת" 20ms.1000 lines, each import "waits for the network" 20ms.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.thenComposethenCompose
findId(title) ו-loadAuthor(id) מחזירות שתיהן CompletableFuture.findId(title) and loadAuthor(id) both return a CompletableFuture.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.וירטואלי מול רגילVirtual vs platform
- צרו thread וירטואלי עם
Thread.ofVirtual().start(...) ו-thread רגיל עם Thread.ofPlatform().start(...).Create a virtual thread with Thread.ofVirtual().start(...) and a platform thread with Thread.ofPlatform().start(...).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנוWhat we learned
- CompletableFuture: Future שאפשר לשרשר:CompletableFuture: A Future you can chain:
supplyAsync מריץ את fetchTitle ב-thread אחר.supplyAsync runs fetchTitle on another thread.thenCombine מחכה לשתי משימות ומחבר את התוצאות.thenCombine waits for two tasks and combines the results.- כל משימה ישנה 10ms.Each task sleeps 10ms.
- `java.util.concurrent.CompletionException:`java.util.concurrent.CompletionException:
- מדף, צעד 37: ייבוא עם virtual threadsShelf, step 37: import with virtual threads
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.