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

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

מה נעשה היוםToday's plan

  • מונחיםTerms
  • wait ו-notifyAllwait and notifyAll
  • BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without wait
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

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

פרויקט מדףShelf project

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

  • מדף, צעד 34: תור ייבואShelf, step 34: an import queue

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".

הצרכן נועל, ובודק ב-while אם יש חבילה.The consumer locks, and checks in a while whether there's a parcel.

אין?None?

wait() משחרר את המנעול ונרדם.wait() releases the lock and sleeps.

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.

מדף, צעד 34: תור ייבואShelf, step 34: an import queue

למה בודקים את התנאי של 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

כי thread עלול להתעורר כשהתנאי עדיין לא מתקייםBecause a thread may wake while the condition still isn't true

מה עושה wait() עם המנעול?What does wait() do with the lock?

  • משחרר אותו בזמן ההמתנהReleases it while waiting
  • מחזיק אותוKeeps it
  • מוחק אותוDeletes it
  • שום דברNothing

משחרר אותו בזמן ההמתנהReleases it while waiting

מה עושה take() על BlockingQueue ריק?What does take() do on an empty BlockingQueue?

  • מחכה עד שיש משהוWaits until something arrives
  • מחזיר nullReturns null
  • זורק חריגהThrows
  • מחזיר 0Returns 0

מחכה עד שיש משהוWaits until something arrives

מחכים לחבילהWaiting for a parcel

  • כתבו את הצרכן מהתזכורת:Write the consumer from the refresher:

תור חסום בעצמכם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.

צייד באגים: 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:

תור בגודל 1A queue of size 1

  • שנו את הדוגמה מהתזכורת לתור בגודל 1 ושלושה פריטים.Change the refresher example to a queue of size 1 and three items.

מדף, צעד 34: תור ייבואShelf, step 34: an import queue

  • main (הקורא) שם שורות Title;Author ב-LinkedBlockingQueue.main (the reader) puts Title;Author lines into a LinkedBlockingQueue.

CountDownLatchCountDownLatch

  • שלושה טוענים מדפיסים loader N ready וקוראים ל-countDown().Three loaders print loader N ready and call countDown().

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.

wait ו-notifyAll רק בתוך synchronized (lock), אחרת IllegalMonitorStateException.wait and notifyAll only inside synchronized (lock), or you get IllegalMonitorStateException.

while (items.size() == cap) wait();while (items.size() == cap) wait();

עם while, אם ready כבר true, לא מחכים בכלל.With while, if ready is already true, you don't wait at all.

new ArrayBlockingQueue<>(1)new ArrayBlockingQueue<>(1)

גלולת רעל לכל צרכן, אחרת אחד מהם יחכה לנצח.A poison pill per consumer, otherwise one of them waits forever.

new CountDownLatch(3)new CountDownLatch(3)

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

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

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

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