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

חזרה למפגשBack
JavaJava

Race conditions, synchronized ומוניטוריםRace conditions, synchronized & monitors

מפגש 32: למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים.Session 32: Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors.

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

  • מונחיםTerms
  • count++ מאבד עדכוניםcount++ loses updates
  • synchronized: אחד בכל פעםsynchronized: one at a time
  • בדיקה ואז פעולהCheck, then act
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

המונחים של המפגשThis session's terms

  • מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.race condition: A result that depends on the order threads run in.
  • קטע קריטי: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.critical section: Code touching something shared, that only one thread should run at a time.
  • synchronized: synchronized void inc() או `synchronized (lock) { ...synchronized: synchronized void inc() or `synchronized (lock) { ...
  • מוניטור: המנעול המובנה של כל עצם ב-Java.monitor: The built-in lock every Java object has.
  • reentrant: thread שכבר מחזיק מנעול יכול להיכנס אליו שוב (למשל מתודה synchronized שקוראת למתודה synchronized אחרת של אותו עצם) בלי לחסום את עצמו.reentrant: A thread already holding a lock can enter it again (e.g.
  • בדיקה ואז פעולה: if (copies > 0) copies--;:check-then-act: if (copies > 0) copies--;:
נושאTopic 2

count++ מאבד עדכוניםcount++ loses updates

count++ מאבד עדכוניםcount++ loses updates

  • שני threads מגדילים מונה 100,000 פעמים כל אחד.Two threads increment a counter 100,000 times each.
  • היינו מצפים ל-200,000.We'd expect 200,000.
  • הטבלה מראה מה באמת יצא ב-10 הרצות אמיתיות.The table shows what really came out in 10 real runs.
נושאTopic 3

synchronized: אחד בכל פעםsynchronized: one at a time

synchronized: אחד בכל פעםsynchronized: one at a time

  • עם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים.With synchronized, increment becomes a critical section: only one thread inside.
  • התוצאה תמיד 200,000.The result is always 200,000.
נושאTopic 4

בדיקה ואז פעולהCheck, then act

בדיקה ואז פעולהCheck, then act

  • עותק אחד, שני אנשים.One copy, two people.
  • כל אחד בודק copies > 0 ואז מוריד.Each checks copies > 0 then decrements.
  • בין הבדיקה להורדה (Thread.yield() נותן הזדמנות) השני יכול לעבור את הבדיקה גם.Between the check and the decrement (Thread.yield() gives a chance) the other can pass the check too.
נושאTopic 5

פרויקט מדףShelf project

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

  • מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter

מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.race condition: A result that depends on the order threads run in.

קטע קריטי: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.critical section: Code touching something shared, that only one thread should run at a time.

synchronized: synchronized void inc() או `synchronized (lock) { ...synchronized: synchronized void inc() or `synchronized (lock) { ...

מוניטור: המנעול המובנה של כל עצם ב-Java.monitor: The built-in lock every Java object has.

reentrant: thread שכבר מחזיק מנעול יכול להיכנס אליו שוב (למשל מתודה synchronized שקוראת למתודה synchronized אחרת של אותו עצם) בלי לחסום את עצמו.reentrant: A thread already holding a lock can enter it again (e.g.

בדיקה ואז פעולה: if (copies > 0) copies--;:check-then-act: if (copies > 0) copies--;:

שני threads מגדילים מונה 100,000 פעמים כל אחד.Two threads increment a counter 100,000 times each.

היינו מצפים ל-200,000.We'd expect 200,000.

הטבלה מראה מה באמת יצא ב-10 הרצות אמיתיות.The table shows what really came out in 10 real runs.

עם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים.With synchronized, increment becomes a critical section: only one thread inside.

התוצאה תמיד 200,000.The result is always 200,000.

עותק אחד, שני אנשים.One copy, two people.

כל אחד בודק copies > 0 ואז מוריד.Each checks copies > 0 then decrements.

בין הבדיקה להורדה (Thread.yield() נותן הזדמנות) השני יכול לעבור את הבדיקה גם.Between the check and the decrement (Thread.yield() gives a chance) the other can pass the check too.

מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter

למה count++ לא בטוח בין threads?Why isn't count++ safe between threads?

  • כי זה קריאה, חישוב וכתיבה, ו-thread אחר יכול להיכנס באמצעBecause it's a read, a calculation and a write, and another thread can slip in between
  • כי int קטן מדיBecause int is too small
  • זה בטוחIt is safe
  • כי Java איטיתBecause Java is slow

כי זה קריאה, חישוב וכתיבה, ו-thread אחר יכול להיכנס באמצעBecause it's a read, a calculation and a write, and another thread can slip in between

שתי מתודות synchronized רגילות של אותו עצם. שני threads קוראים לכל אחת. מה קורה?Two plain synchronized methods of the same object. Two threads call one each. What happens?

  • הן לא רצות בו זמנית: שתיהן נועלות את thisThey don't run at the same time: both lock this
  • הן רצות במקבילThey run in parallel
  • deadlockdeadlock
  • שגיאת קומפילציהA compile error

הן לא רצות בו זמנית: שתיהן נועלות את thisThey don't run at the same time: both lock this

מתודה synchronized קוראת למתודה synchronized אחרת של אותו עצם. מה קורה?A synchronized method calls another synchronized method of the same object. What happens?

  • עובד: המנעול reentrantIt works: the lock is reentrant
  • ה-thread חוסם את עצמוThe thread blocks itself
  • חריגהAn exception
  • תלוי במזלIt depends on luck

עובד: המנעול reentrantIt works: the lock is reentrant

מונה בטוח, ארבעה threadsA safe counter, four threads

  • Counter עם synchronized על increment ועל get.Counter with synchronized on increment and get.

בלוק synchronizedA synchronized block

  • שני threads מוסיפים כל אחד 1000 מספרים ל-ArrayList משותפת.Two threads each add 1000 numbers to a shared ArrayList.

צייד באגים: עדכונים אבודיםBug hunter: lost updates

  • התוכנית מהתזכורת מדפיסה מספר שונה בכל הרצה, ובדרך כלל פחות מ-200,000.The program from the refresher prints a different number each run, usually less than 200,000.

עשרה אנשים, שלושה עותקיםTen people, three copies

  • ל-Shelf יש 3 עותקים.Shelf has 3 copies.

מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter

  • LoanCounter סופר השאלות לפי כותר ובסך הכול.LoanCounter counts loans per title and in total.

static synchronizedstatic synchronized

  • מונה static ומתודה static synchronized void visit() (נועלת את המחלקה).A static counter and a static synchronized void visit() method (it locks the class).

מנעול שנכנסים אליו שובA lock you can re-enter

  • transferIn היא synchronized וקוראת ל-deposit (גם synchronized) פעמיים.transferIn is synchronized and calls deposit (also synchronized) twice.

מה למדנוWhat we learned

  • מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.race condition: A result that depends on the order threads run in.
  • שני threads מגדילים מונה 100,000 פעמים כל אחד.Two threads increment a counter 100,000 times each.
  • עם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים.With synchronized, increment becomes a critical section: only one thread inside.
  • עותק אחד, שני אנשים.One copy, two people.
  • מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter

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

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

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