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

JavaJava
35
חלק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.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-IntelliJ ולסמן פתרתי. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in IntelliJ and mark I solved it. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. למה להשתמש בבריכה במקום new Thread לכל משימה?Why use a pool instead of new Thread per task?

2. משימה זרקה חריגה. מה עושה future.get()?A task threw an exception. What does future.get() do?

3. מה קורה אם שוכחים shutdown()?What happens if you forget shutdown()?

תרגיליםExercises

תרגילExercise 1

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

בריכה של 3 threads. ארבע משימות (Callable) סוכמות כל אחת 250 מספרים (1–250, 251–500 וכו'). אספו את ה-Futures, חברו, והדפיסו 500500.

A pool of 3 threads. Four tasks (Callables) each sum 250 numbers (1–250, 251–500 and so on). Collect the Futures, add, and print 500500.

איך הפלט אמור להיראות?What should the output look like?
500500
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: משתנים בתוך הלולאה (from, to) כדי שהלמבדה תוכל להשתמש בהם.Variables inside the loop (from, to) so the lambda can use them.
לפתרוןSolution
תרגילExercise 2

invokeAllinvokeAll

שלוש משימות מחזירות את אורך הכותר כמחרוזת. הריצו עם invokeAll על בריכה של 2 והדפיסו [4, 4, 7] (בסדר המשימות).

Three tasks return the title's length as a string. Run them with invokeAll on a pool of 2 and print [4, 4, 7] (in task order).

איך הפלט אמור להיראות?What should the output look like?
[4, 4, 7]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: pool.invokeAll(jobs) מחכה שכולן יסתיימו.pool.invokeAll(jobs) waits for them all to finish.
לפתרוןSolution
תרגילExercise 3

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

המשימה מנסה להמיר 19x5 ונכשלת, ו-get() מפיל את main. תפסו את ExecutionException, הדפיסו task failed: NumberFormatException, וסגרו את הבריכה ב-finally.

The task tries to parse 19x5 and fails, and get() crashes main. Catch the ExecutionException, print task failed: NumberFormatException, and shut the pool in finally.

איך הפלט אמור להיראות?What should the output look like?
task failed: NumberFormatException
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: e.getCause().getClass().getSimpleName()e.getCause().getClass().getSimpleName()
לפתרוןSolution
תרגילExercise 4

executor של thread אחדA single-thread executor

Executors.newSingleThreadExecutor() מריץ משימות אחת אחרי השנייה, לפי הסדר, ולכן ArrayList רגילה בטוחה כאן. שלחו open, read, close, סגרו, חכו, והדפיסו [open, read, close].

Executors.newSingleThreadExecutor() runs tasks one after another, in order, so a plain ArrayList is safe here. Submit open, read, close, shut down, wait, and print [open, read, close].

איך הפלט אמור להיראות?What should the output look like?
[open, read, close]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: awaitTermination לפני שקוראים את הרשימה.awaitTermination before reading the list.
לפתרוןSolution
תרגילExercise 5

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

פרויקט מלווהCompanion 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.

איך הפלט אמור להיראות?What should the output look like?
4 books, 1865 pages, first Dune
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: List<Callable<Book>> jobsList<Callable<Book>> jobs
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

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

משימה איטית (2 שניות). get(100, MILLISECONDS) מוותר אחרי 100ms עם TimeoutException. בטלו עם cancel(true) והדפיסו too slow, cancelling: true ואז cancelled=true.

A slow task (2 seconds). get(100, MILLISECONDS) gives up after 100ms with a TimeoutException. Cancel with cancel(true) and print too slow, cancelling: true then cancelled=true.

איך הפלט אמור להיראות?What should the output look like?
too slow, cancelling: true
cancelled=true
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: cancel(true) שולח interrupt ל-thread, ו-sleep עוצר.cancel(true) interrupts the thread, and sleep stops.
לפתרוןSolution
אתגרChallenge 2

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

שני "שרתי מראה" מחזירים ספר, אחד איטי ואחד מהיר. invokeAny מחזיר את התוצאה הראשונה ומבטל את השאר. הדפיסו got the book from the fast mirror.

Two "mirror servers" return a book, one slow and one fast. invokeAny returns the first result and cancels the rest. Print got the book from the fast mirror.

איך הפלט אמור להיראות?What should the output look like?
got the book from the fast mirror
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: pool.invokeAny(List.of(...))pool.invokeAny(List.of(...))
לפתרוןSolution

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