נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
wait/notify, producer/consumer ו-BlockingQueuewait/notify, producer/consumer & BlockingQueue
מפגש 34: המתנה לתנאי עם wait ו-notify, תבנית יצרן-צרכן, ו-BlockingQueue שעושה את זה בשבילכם.Session 34: Waiting for a condition with wait and notify, the producer-consumer pattern, and BlockingQueue that does it for you.
המתנה לתנאי עם wait ו-notify, תבנית יצרן-צרכן, ו-BlockingQueue שעושה את זה בשבילכם. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Waiting for a condition with wait and notify, the producer-consumer pattern, and BlockingQueue that does it for you. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- wait ו-notifyAllwait and notifyAll
- BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without wait
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- wait ו-notify:
lock.wait() משחרר את המנעול ונרדם עד ש-lock.notifyAll() מעיר אותו (ואז הוא מחכה לקבל את המנעול שוב).wait and notify: lock.wait() releases the lock and sleeps until lock.notifyAll() wakes it (then it waits to get the lock back). - התעוררות שקרית: thread יכול להתעורר מ-wait בלי סיבה, או אחרי שמישהו אחר כבר לקח את מה שחיכה לו.spurious wakeup: A thread can wake from wait for no reason, or after someone else already took what it waited for.
- יצרן-צרכן: thread אחד (או יותר) מייצר עבודה ושם בתור, ואחרים לוקחים ומעבדים.producer-consumer: One thread (or more) produces work into a queue, and others take and process it.
- BlockingQueue: תור בטוח ל-threads:BlockingQueue: A thread-safe queue:
- גלולת רעל: ערך מיוחד שהיצרן שם בתור כדי לומר לצרכן "זהו, אפשר לסיים".poison pill: A special value the producer puts in the queue to tell a consumer "that's it, you can stop".
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
wait ו-notifyAllwait and notifyAll
wait ו-notifyAllwait and notifyAll
- הצרכן נועל, ובודק ב-
while אם יש חבילה.The consumer locks, and checks in a while whether there's a parcel. - אין?None?
wait() משחרר את המנעול ונרדם.wait() releases the lock and sleeps.
הצרכן נועל, ובודק ב-while אם יש חבילה. אין? wait() משחרר את המנעול ונרדם. main שם חבילה ו-notifyAll(). הצרכן מתעורר, מקבל שוב את המנעול, בודק שוב, ומדפיס.The consumer locks, and checks in a while whether there's a parcel. None? wait() releases the lock and sleeps. main puts a parcel and calls notifyAll(). The consumer wakes, gets the lock back, checks again, and prints.נושאTopic 3
BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without wait
BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without wait
ArrayBlockingQueue בגודל 2: היצרן נחסם כשהתור מלא, והצרכן נחסם כשהוא ריק.An ArrayBlockingQueue of size 2: the producer blocks when the queue is full, the consumer blocks when it's empty.- הסדר
processed 1..5 מובטח, כי זה תור.The order processed 1..5 is guaranteed, because it's a queue.
ArrayBlockingQueue בגודל 2: היצרן נחסם כשהתור מלא, והצרכן נחסם כשהוא ריק. הסדר processed 1..5 מובטח, כי זה תור.An ArrayBlockingQueue of size 2: the producer blocks when the queue is full, the consumer blocks when it's empty. The order processed 1..5 is guaranteed, because it's a queue.נושאTopic 4
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 34: תור ייבואShelf, step 34: an import queue
main (הקורא) שם שורות Title;Author ב-LinkedBlockingQueue. שני מעבדים לוקחים שורות וסופרים ספרים לפי סופר במפה משותפת (מוגנת). בסוף main שם <done> פעמיים (אחד לכל מעבד). הדפיסו {Austen=2, Herbert=2, Joyce=1}.main (the reader) puts Title;Author lines into a LinkedBlockingQueue. Two processors take lines and count books per author in a shared (protected) map. At the end main puts <done> twice (one per processor). Print {Austen=2, Herbert=2, Joyce=1}.wait ו-notify: lock.wait() משחרר את המנעול ונרדם עד ש-lock.notifyAll() מעיר אותו (ואז הוא מחכה לקבל את המנעול שוב).wait and notify: lock.wait() releases the lock and sleeps until lock.notifyAll() wakes it (then it waits to get the lock back).
המונחים של המפגשThis session's termsהתעוררות שקרית: thread יכול להתעורר מ-wait בלי סיבה, או אחרי שמישהו אחר כבר לקח את מה שחיכה לו.spurious wakeup: A thread can wake from wait for no reason, or after someone else already took what it waited for.
המונחים של המפגשThis session's termsיצרן-צרכן: thread אחד (או יותר) מייצר עבודה ושם בתור, ואחרים לוקחים ומעבדים.producer-consumer: One thread (or more) produces work into a queue, and others take and process it.
המונחים של המפגשThis session's termsBlockingQueue: תור בטוח ל-threads:BlockingQueue: A thread-safe queue:
המונחים של המפגשThis session's termsגלולת רעל: ערך מיוחד שהיצרן שם בתור כדי לומר לצרכן "זהו, אפשר לסיים".poison pill: A special value the producer puts in the queue to tell a consumer "that's it, you can stop".
המונחים של המפגשThis session's termsהצרכן נועל, ובודק ב-while אם יש חבילה.The consumer locks, and checks in a while whether there's a parcel.
wait ו-notifyAllwait and notifyAllאין?None?
wait ו-notifyAllwait and notifyAllwait() משחרר את המנעול ונרדם.wait() releases the lock and sleeps.
wait ו-notifyAllwait and notifyAllArrayBlockingQueue בגודל 2: היצרן נחסם כשהתור מלא, והצרכן נחסם כשהוא ריק.An ArrayBlockingQueue of size 2: the producer blocks when the queue is full, the consumer blocks when it's empty.
BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without waitהסדר processed 1..5 מובטח, כי זה תור.The order processed 1..5 is guaranteed, because it's a queue.
BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without waitמדף, צעד 34: תור ייבואShelf, step 34: an import queue
הצעד של היום בפרויקט מדףToday's step in the Shelf projectלמה בודקים את התנאי של wait ב-while ולא ב-if?Why check wait's condition in a while and not an if?
- כי thread עלול להתעורר כשהתנאי עדיין לא מתקייםBecause a thread may wake while the condition still isn't true
- כי
if לא עובד עם waitBecause if doesn't work with wait - סתם סגנוןJust style
- כדי שירוץ מהרSo it runs fast
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כי thread עלול להתעורר כשהתנאי עדיין לא מתקייםBecause a thread may wake while the condition still isn't true
נכון.Right.מה עושה wait() עם המנעול?What does wait() do with the lock?
- משחרר אותו בזמן ההמתנהReleases it while waiting
- מחזיק אותוKeeps it
- מוחק אותוDeletes it
- שום דברNothing
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.משחרר אותו בזמן ההמתנהReleases it while waiting
נכון, אחרת אף אחד לא היה יכול לשלוח notify.Right, otherwise nobody could send notify.מה עושה take() על BlockingQueue ריק?What does take() do on an empty BlockingQueue?
- מחכה עד שיש משהוWaits until something arrives
- מחזיר nullReturns null
- זורק חריגהThrows
- מחזיר 0Returns 0
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.מחכה עד שיש משהוWaits until something arrives
נכון.Right.מחכים לחבילהWaiting for a parcel
- כתבו את הצרכן מהתזכורת:Write the consumer from the refresher:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.תור חסום בעצמכםA bounded queue of your own
Box בגודל 2 עם synchronized put (מחכה כשמלא) ו-synchronized take (מחכה כשריק), שתיהן קוראות ל-notifyAll() אחרי שינוי.Box of size 2 with a synchronized put (waits when full) and a synchronized take (waits when empty), both calling notifyAll() after a change.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: notify שהלך לאיבודBug hunter: a lost notify
- כאן ה-notify נשלח לפני שה-waiter בכלל התחיל, וה-waiter קורא ל-
wait() בלי לבדוק תנאי:Here the notify is sent before the waiter even started, and the waiter calls wait() without checking a condition:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.תור בגודל 1A queue of size 1
- שנו את הדוגמה מהתזכורת לתור בגודל 1 ושלושה פריטים.Change the refresher example to a queue of size 1 and three items.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 34: תור ייבואShelf, step 34: an import queue
- main (הקורא) שם שורות
Title;Author ב-LinkedBlockingQueue.main (the reader) puts Title;Author lines into a LinkedBlockingQueue.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.CountDownLatchCountDownLatch
- שלושה טוענים מדפיסים
loader N ready וקוראים ל-countDown().Three loaders print loader N ready and call countDown().
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.poll עם זמן קצובpoll with a timeout
q.poll(50, TimeUnit.MILLISECONDS) מחכה עד 50ms ומחזיר null אם לא הגיע כלום.q.poll(50, TimeUnit.MILLISECONDS) waits up to 50ms and returns null if nothing came.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.wait ו-notifyAll רק בתוך synchronized (lock), אחרת IllegalMonitorStateException.wait and notifyAll only inside synchronized (lock), or you get IllegalMonitorStateException.
מחכים לחבילהWaiting for a parcelwhile (items.size() == cap) wait();while (items.size() == cap) wait();
תור חסום בעצמכםA bounded queue of your ownעם while, אם ready כבר true, לא מחכים בכלל.With while, if ready is already true, you don't wait at all.
צייד באגים: notify שהלך לאיבודBug hunter: a lost notifynew ArrayBlockingQueue<>(1)new ArrayBlockingQueue<>(1)
תור בגודל 1A queue of size 1גלולת רעל לכל צרכן, אחרת אחד מהם יחכה לנצח.A poison pill per consumer, otherwise one of them waits forever.
מדף, צעד 34: תור ייבואShelf, step 34: an import queuenew CountDownLatch(3)new CountDownLatch(3)
CountDownLatchCountDownLatchמה למדנוWhat we learned
- wait ו-notify:
lock.wait() משחרר את המנעול ונרדם עד ש-lock.notifyAll() מעיר אותו (ואז הוא מחכה לקבל את המנעול שוב).wait and notify: lock.wait() releases the lock and sleeps until lock.notifyAll() wakes it (then it waits to get the lock back). - הצרכן נועל, ובודק ב-
while אם יש חבילה.The consumer locks, and checks in a while whether there's a parcel. ArrayBlockingQueue בגודל 2: היצרן נחסם כשהתור מלא, והצרכן נחסם כשהוא ריק.An ArrayBlockingQueue of size 2: the producer blocks when the queue is full, the consumer blocks when it's empty.- מדף, צעד 34: תור ייבואShelf, step 34: an import queue
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.