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

חזרה למפגשBack
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.

מה נעשה היום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
נושאTopic 1

מונחיםTerms

המונחים של המפגש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.
נושא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.
נושא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.
נושא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.
נושאTopic 5

טעויות נפוצותCommon mistakes

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

  • `java.util.concurrent.ExecutionException:`java.util.concurrent.ExecutionException:
נושאTopic 6

פרויקט מדףShelf project

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

  • מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import

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.

ארבע משימות, רק שני 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.

כל משימה מחזירה את אורך הכותר.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.

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

למה להשתמש בבריכה במקום 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

יצירת thread יקרה, ובריכה משתמשת שוב באותם threads ומגבילה כמה רצים יחדCreating a thread is expensive, and a pool reuses threads and limits how many run together

משימה זרקה חריגה. מה עושה 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

זורק ExecutionException, והחריגה המקורית ב-getCause()Throws an ExecutionException, with the original in getCause()

מה קורה אם שוכחים 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

ה-threads של הבריכה ממשיכים לחכות, והתוכנית לא מסתיימתThe pool's threads keep waiting, and the program doesn't end

סכום בארבעה חלקיםA sum in four parts

  • בריכה של 3 threads.A pool of 3 threads.

invokeAllinvokeAll

  • שלוש משימות מחזירות את אורך הכותר כמחרוזת.Three tasks return the title's length as a string.

צייד באגים: משימה שנכשלהBug hunter: a task that failed

  • המשימה מנסה להמיר 19x5 ונכשלת, ו-get() מפיל את main.The task tries to parse 19x5 and fails, and get() crashes main.

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.

מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import

  • כל שורה Title;Pages מיובאת במשימה משלה (importLine).Each Title;Pages line is imported in its own task (importLine).

זמן קצוב וביטולA timeout and a cancel

  • משימה איטית (2 שניות).A slow task (2 seconds).

invokeAny: הראשון שמצליחinvokeAny: the first to succeed

  • שני "שרתי מראה" מחזירים ספר, אחד איטי ואחד מהיר.Two "mirror servers" return a book, one slow and one fast.

מה למדנו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

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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