נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
ExecutorService, thread pools, Callable ו-FutureExecutorService, thread pools, Callable & Future
מפגש 35: בריכת threads, משימות עם תוצאה, Future.get, invokeAll, וסגירה מסודרת.Session 35: Thread pools, tasks with a result, Future.get, invokeAll, and an orderly shutdown.
בריכת threads, משימות עם תוצאה, Future.get, invokeAll, וסגירה מסודרת. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Thread pools, tasks with a result, Future.get, invokeAll, and an orderly shutdown. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- בריכה של שני threads, ארבע משימותA pool of two threads, four tasks
- Callable ו-FutureCallable and Future
- invokeAll שומר על הסדרinvokeAll keeps the order
- טעויות נפוצותCommon mistakes
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- ExecutorService: שירות שמקבל משימות (
submit) ומריץ אותן על threads שהוא מנהל.ExecutorService: A service that takes tasks (submit) and runs them on threads it manages. - בריכת threads: מספר קבוע של threads שלוקחים משימות מתור.thread pool: A fixed number of threads taking tasks from a queue.
- Callable: כמו Runnable, אבל מחזיר ערך ויכול לזרוק חריגה:Callable: Like Runnable, but returns a value and may throw:
- Future: "קבלה" על תוצאה שעוד תגיע.Future: A "receipt" for a result still to come.
- shutdown:
shutdown() מפסיק לקבל משימות חדשות ונותן לקיימות לסיים.shutdown: shutdown() stops taking new tasks and lets the current ones finish.
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
בריכה של שני threads, ארבע משימותA pool of two threads, four tasks
בריכה של שני threads, ארבע משימותA pool of two threads, four tasks
- ארבע משימות, רק שני threads (
pool-1-thread-1, pool-1-thread-2).Four tasks, only two threads (pool-1-thread-1, pool-1-thread-2). - כל thread לוקח משימה, מסיים, ולוקח את הבאה.Each thread takes a task, finishes it, and takes the next.
- הסדר והחלוקה משתנים, וזה מה שהטבלה מראה.The order and the split change, which is what the table shows.
ארבע משימות, רק שני threads (pool-1-thread-1, pool-1-thread-2). כל thread לוקח משימה, מסיים, ולוקח את הבאה. הסדר והחלוקה משתנים, וזה מה שהטבלה מראה.Four tasks, only two threads (pool-1-thread-1, pool-1-thread-2). Each thread takes a task, finishes it, and takes the next. The order and the split change, which is what the table shows.נושאTopic 3
Callable ו-FutureCallable and Future
Callable ו-FutureCallable and Future
- כל משימה מחזירה את אורך הכותר.Each task returns the title's length.
f.get() מחכה לתוצאה.f.get() waits for the result.- הסכום תמיד
letters: 15, גם כשהמשימות מסתיימות בסדר אחר.The sum is always letters: 15, even when tasks finish in another order.
כל משימה מחזירה את אורך הכותר. f.get() מחכה לתוצאה. הסכום תמיד letters: 15, גם כשהמשימות מסתיימות בסדר אחר.Each task returns the title's length. f.get() waits for the result. The sum is always letters: 15, even when tasks finish in another order.נושאTopic 4
invokeAll שומר על הסדרinvokeAll keeps the order
invokeAll שומר על הסדרinvokeAll keeps the order
invokeAll מחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.invokeAll returns the Futures in the order you gave the tasks, not the order they finished.
invokeAll מחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.invokeAll returns the Futures in the order you gave the tasks, not the order they finished.נושאTopic 5
טעויות נפוצותCommon mistakes
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
- `java.util.concurrent.ExecutionException:`java.util.concurrent.ExecutionException:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-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
- מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import
כל שורה Title;Pages מיובאת במשימה משלה (importLine). הריצו עם invokeAll על בריכה של 2, אספו Bookים לפי הסדר, והדפיסו 4 books, 1865 pages, first Dune.Each Title;Pages line is imported in its own task (importLine). Run them with invokeAll on a pool of 2, collect Books in order, and print 4 books, 1865 pages, first Dune.ExecutorService: שירות שמקבל משימות (submit) ומריץ אותן על threads שהוא מנהל.ExecutorService: A service that takes tasks (submit) and runs them on threads it manages.
המונחים של המפגשThis session's termsבריכת threads: מספר קבוע של threads שלוקחים משימות מתור.thread pool: A fixed number of threads taking tasks from a queue.
המונחים של המפגשThis session's termsCallable: כמו Runnable, אבל מחזיר ערך ויכול לזרוק חריגה:Callable: Like Runnable, but returns a value and may throw:
המונחים של המפגשThis session's termsFuture: "קבלה" על תוצאה שעוד תגיע.Future: A "receipt" for a result still to come.
המונחים של המפגשThis session's termsshutdown: shutdown() מפסיק לקבל משימות חדשות ונותן לקיימות לסיים.shutdown: shutdown() stops taking new tasks and lets the current ones finish.
המונחים של המפגשThis session's termsארבע משימות, רק שני threads (pool-1-thread-1, pool-1-thread-2).Four tasks, only two threads (pool-1-thread-1, pool-1-thread-2).
בריכה של שני threads, ארבע משימותA pool of two threads, four tasksכל thread לוקח משימה, מסיים, ולוקח את הבאה.Each thread takes a task, finishes it, and takes the next.
בריכה של שני threads, ארבע משימותA pool of two threads, four tasksהסדר והחלוקה משתנים, וזה מה שהטבלה מראה.The order and the split change, which is what the table shows.
בריכה של שני threads, ארבע משימותA pool of two threads, four tasksכל משימה מחזירה את אורך הכותר.Each task returns the title's length.
Callable ו-FutureCallable and Futuref.get() מחכה לתוצאה.f.get() waits for the result.
Callable ו-FutureCallable and Futureהסכום תמיד letters: 15, גם כשהמשימות מסתיימות בסדר אחר.The sum is always letters: 15, even when tasks finish in another order.
Callable ו-FutureCallable and FutureinvokeAll מחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.invokeAll returns the Futures in the order you gave the tasks, not the order they finished.
invokeAll שומר על הסדרinvokeAll keeps the order`java.util.concurrent.ExecutionException:`java.util.concurrent.ExecutionException:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import
הצעד של היום בפרויקט מדףToday's step in the Shelf projectלמה להשתמש בבריכה במקום new Thread לכל משימה?Why use a pool instead of new Thread per task?
- יצירת thread יקרה, ובריכה משתמשת שוב באותם threads ומגבילה כמה רצים יחדCreating a thread is expensive, and a pool reuses threads and limits how many run together
- כי Thread לא עובדBecause Thread doesn't work
- כי זה מבטיח סדרBecause it guarantees order
- אין הבדלNo difference
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.יצירת thread יקרה, ובריכה משתמשת שוב באותם threads ומגבילה כמה רצים יחדCreating a thread is expensive, and a pool reuses threads and limits how many run together
נכון.Right.משימה זרקה חריגה. מה עושה future.get()?A task threw an exception. What does future.get() do?
- זורק
ExecutionException, והחריגה המקורית ב-getCause()Throws an ExecutionException, with the original in getCause() - מחזיר nullReturns null
- החריגה נעלמתThe exception vanishes
- התוכנית קורסת מידThe program crashes at once
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.זורק ExecutionException, והחריגה המקורית ב-getCause()Throws an ExecutionException, with the original in getCause()
נכון.Right.מה קורה אם שוכחים shutdown()?What happens if you forget shutdown()?
- ה-threads של הבריכה ממשיכים לחכות, והתוכנית לא מסתיימתThe pool's threads keep waiting, and the program doesn't end
- כלוםNothing
- המשימות לא רצותThe tasks don't run
- שגיאת קומפילציהA compile error
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.ה-threads של הבריכה ממשיכים לחכות, והתוכנית לא מסתיימתThe pool's threads keep waiting, and the program doesn't end
נכון.Right.סכום בארבעה חלקיםA sum in four parts
- בריכה של 3 threads.A pool of 3 threads.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.invokeAllinvokeAll
- שלוש משימות מחזירות את אורך הכותר כמחרוזת.Three tasks return the title's length as a string.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: משימה שנכשלהBug hunter: a task that failed
- המשימה מנסה להמיר
19x5 ונכשלת, ו-get() מפיל את main.The task tries to parse 19x5 and fails, and get() crashes main.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.executor של thread אחדA single-thread executor
Executors.newSingleThreadExecutor() מריץ משימות אחת אחרי השנייה, לפי הסדר, ולכן ArrayList רגילה בטוחה כאן.Executors.newSingleThreadExecutor() runs tasks one after another, in order, so a plain ArrayList is safe here.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import
- כל שורה
Title;Pages מיובאת במשימה משלה (importLine).Each Title;Pages line is imported in its own task (importLine).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.זמן קצוב וביטולA timeout and a cancel
- משימה איטית (2 שניות).A slow task (2 seconds).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.invokeAny: הראשון שמצליחinvokeAny: the first to succeed
- שני "שרתי מראה" מחזירים ספר, אחד איטי ואחד מהיר.Two "mirror servers" return a book, one slow and one fast.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנוWhat we learned
- ExecutorService: שירות שמקבל משימות (
submit) ומריץ אותן על threads שהוא מנהל.ExecutorService: A service that takes tasks (submit) and runs them on threads it manages. - ארבע משימות, רק שני threads (
pool-1-thread-1, pool-1-thread-2).Four tasks, only two threads (pool-1-thread-1, pool-1-thread-2). - כל משימה מחזירה את אורך הכותר.Each task returns the title's length.
invokeAll מחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.invokeAll returns the Futures in the order you gave the tasks, not the order they finished.- `java.util.concurrent.ExecutionException:`java.util.concurrent.ExecutionException:
- מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.