חלקPart 6: Concurrency ו-ThreadsConcurrency & threads
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
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.
הנקודות החשובותKey points
- 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.
- ארבע משימות, רק שני 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.
- כל משימה מחזירה את אורך הכותר.Each task returns the title's length.
f.get()מחכה לתוצאה.f.get()waits for the result.invokeAllמחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.invokeAllreturns 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
מונחיםTerms
- ExecutorServiceExecutorService: שירות שמקבל משימות (
submit) ומריץ אותן על threads שהוא מנהל. נוצר עםExecutors.newFixedThreadPool(n)ודומיו.A service that takes tasks (submit) and runs them on threads it manages. Created withExecutors.newFixedThreadPool(n)and friends. - בריכת threadsthread pool: מספר קבוע של threads שלוקחים משימות מתור. יצירת thread יקרה, ולכן משתמשים שוב באותם threads.A fixed number of threads taking tasks from a queue. Creating a thread is expensive, so the same threads are reused.
- CallableCallable: כמו Runnable, אבל מחזיר ערך ויכול לזרוק חריגה:
Callable<Integer> job = () -> 42;.Like Runnable, but returns a value and may throw:Callable<Integer> job = () -> 42;. - FutureFuture: "קבלה" על תוצאה שעוד תגיע.
get()מחכה לה; אם המשימה נכשלה,get()זורקExecutionExceptionשהחריגה המקורית היא ה-cause שלה.A "receipt" for a result still to come.get()waits for it; if the task failed,get()throws anExecutionExceptionwhose cause is the original exception. - shutdownshutdown:
shutdown()מפסיק לקבל משימות חדשות ונותן לקיימות לסיים.awaitTerminationמחכה לזה. בלי shutdown התוכנית עלולה לא להסתיים.shutdown()stops taking new tasks and lets the current ones finish.awaitTerminationwaits for that. Without shutdown the program may never end. - ExecutorServiceExecutorService: שירות שמקבל משימות (
submit) ומריץ אותן על threads שהוא מנהל. נוצר עםExecutors.newFixedThreadPool(n)ודומיו.A service that takes tasks (submit) and runs them on threads it manages. Created withExecutors.newFixedThreadPool(n)and friends. - בריכת threadsthread pool: מספר קבוע של threads שלוקחים משימות מתור. יצירת thread יקרה, ולכן משתמשים שוב באותם threads.A fixed number of threads taking tasks from a queue. Creating a thread is expensive, so the same threads are reused.
- CallableCallable: כמו Runnable, אבל מחזיר ערך ויכול לזרוק חריגה:
Callable<Integer> job = () -> 42;.Like Runnable, but returns a value and may throw:Callable<Integer> job = () -> 42;. - FutureFuture: "קבלה" על תוצאה שעוד תגיע.
get()מחכה לה; אם המשימה נכשלה,get()זורקExecutionExceptionשהחריגה המקורית היא ה-cause שלה.A "receipt" for a result still to come.get()waits for it; if the task failed,get()throws anExecutionExceptionwhose cause is the original exception. - shutdownshutdown:
shutdown()מפסיק לקבל משימות חדשות ונותן לקיימות לסיים.awaitTerminationמחכה לזה. בלי shutdown התוכנית עלולה לא להסתיים.shutdown()stops taking new tasks and lets the current ones finish.awaitTerminationwaits for that. Without shutdown the program may never end.
Cheatsheet
בריכה של שני threads, ארבע משימותA pool of two threads, four tasks
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));Callable ו-FutureCallable and Future
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();
}invokeAll שומר על הסדרinvokeAll keeps the order
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);שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
ExecutionException | צייד באגים: משימה שנכשלהBug hunter: a task that failed | 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. |