ExecutorService, thread pools, Callable ו-FutureExecutorService, thread pools, Callable & Future
בריכת threads, משימות עם תוצאה, Future.get, invokeAll, וסגירה מסודרת.
Thread pools, tasks with a result, Future.get, invokeAll, and an orderly shutdown.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- ExecutorService: שירות שמקבל משימות (
submit) ומריץ אותן על threads שהוא מנהל. נוצר עםExecutors.newFixedThreadPool(n)ודומיו.ExecutorService: A service that takes tasks (submit) and runs them on threads it manages. Created withExecutors.newFixedThreadPool(n)and friends. - בריכת threads: מספר קבוע של threads שלוקחים משימות מתור. יצירת thread יקרה, ולכן משתמשים שוב באותם threads.thread pool: A fixed number of threads taking tasks from a queue. Creating a thread is expensive, so the same threads are reused.
- Callable: כמו Runnable, אבל מחזיר ערך ויכול לזרוק חריגה:
Callable<Integer> job = () -> 42;.Callable: Like Runnable, but returns a value and may throw:Callable<Integer> job = () -> 42;. - Future: "קבלה" על תוצאה שעוד תגיע.
get()מחכה לה; אם המשימה נכשלה,get()זורקExecutionExceptionשהחריגה המקורית היא ה-cause שלה.Future: A "receipt" for a result still to come.get()waits for it; if the task failed,get()throws anExecutionExceptionwhose cause is the original exception. - shutdown:
shutdown()מפסיק לקבל משימות חדשות ונותן לקיימות לסיים.awaitTerminationמחכה לזה. בלי shutdown התוכנית עלולה לא להסתיים.shutdown:shutdown()stops taking new tasks and lets the current ones finish.awaitTerminationwaits for that. Without shutdown the program may never end.
02בריכה של שני threads, ארבע משימותA pool of two threads, four tasks
ארבע משימות, רק שני 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.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 1; i <= 4; i++) {
int task = i;
pool.submit(() -> System.out.println("task " + task + " on " + Thread.currentThread().getName()));
}
pool.shutdown();
System.out.println("finished in time: " + pool.awaitTermination(5, TimeUnit.SECONDS));
}
}task 1 on pool-1-thread-1 task 3 on pool-1-thread-1 task 4 on pool-1-thread-1 task 2 on pool-1-thread-2 finished in time: true
10 הרצות אמיתיות בזמן בניית האתר (JDK 21):10 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
task 2 on pool-1-thread-2
task 1 on pool-1-thread-1
task 3 on pool-1-thread-1
task 4 on pool-1-thread-1
finished in time: true | 3 |
task 1 on pool-1-thread-1
task 2 on pool-1-thread-2
task 3 on pool-1-thread-2
task 4 on pool-1-thread-2
finished in time: true | 2 |
task 1 on pool-1-thread-1
task 3 on pool-1-thread-1
task 4 on pool-1-thread-1
task 2 on pool-1-thread-2
finished in time: true | 2 |
task 1 on pool-1-thread-1
task 2 on pool-1-thread-2
task 4 on pool-1-thread-2
task 3 on pool-1-thread-1
finished in time: true | 1 |
task 1 on pool-1-thread-1
task 2 on pool-1-thread-2
task 3 on pool-1-thread-1
task 4 on pool-1-thread-2
finished in time: true | 1 |
task 2 on pool-1-thread-2
task 1 on pool-1-thread-1
task 4 on pool-1-thread-1
task 3 on pool-1-thread-2
finished in time: true | 1 |
מה קורה בתוך thread poolWhat happens inside a thread pool
03Callable ו-FutureCallable and Future
כל משימה מחזירה את אורך הכותר. 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.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
List<Future<Integer>> results = new ArrayList<>();
for (String title : List.of("Dune", "Emma", "Ulysses")) {
Callable<Integer> job = () -> title.length();
results.add(pool.submit(job));
}
int total = 0;
for (Future<Integer> f : results) {
total += f.get();
}
pool.shutdown();
System.out.println("letters: " + total);
}
}letters: 15
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
letters: 15 | 5 |
מה קורה בתוך thread poolWhat happens inside a thread pool
04invokeAll שומר על הסדרinvokeAll keeps the order
invokeAll מחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.
invokeAll returns the Futures in the order you gave the tasks, not the order they finished.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Callable<String>> jobs = List.of(() -> "Dune".toUpperCase(), () -> "Emma".toUpperCase(), () -> "Ulysses".toUpperCase());
List<String> out = new ArrayList<>();
for (Future<String> f : pool.invokeAll(jobs)) {
out.add(f.get());
}
pool.shutdown();
System.out.println(out);
}
}[DUNE, EMMA, ULYSSES]
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
[DUNE, EMMA, ULYSSES] | 5 |
מה קורה בתוך 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.
צייד באגים: משימה שנכשלה
Bug hunter: a task that failed
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> f = pool.submit(() -> Integer.parseInt("19x5"));
pool.shutdown();
System.out.println("year: " + f.get());
}
}Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NumberFormatException: For input string: "19x5" at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) at Main.main(Main.java:14) 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:12) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) at java.base/java.lang.Thread.run(Thread.java:1583)
java.util.concurrent.ExecutionException: java.lang.NumberFormatException: For input string: "19x5": החריגה מהמשימה מגיעה עטופה.java.util.concurrent.ExecutionException: java.lang.NumberFormatException: For input string: "19x5": the task's exception arrives wrapped.06הצעד של היום בפרויקט מדףToday's step in the Shelf project
כל שורה 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.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.