נבנה על ידיBuilt by Ariel Yohimovich
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.
למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- count++ מאבד עדכוניםcount++ loses updates
- synchronized: אחד בכל פעםsynchronized: one at a time
- בדיקה ואז פעולהCheck, then act
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגש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--;:
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושא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.
שני threads מגדילים מונה 100,000 פעמים כל אחד. היינו מצפים ל-200,000. הטבלה מראה מה באמת יצא ב-10 הרצות אמיתיות. בסימולטור תוכלו לייצר את האיבוד בעצמכם.Two threads increment a counter 100,000 times each. We'd expect 200,000. The table shows what really came out in 10 real runs. In the simulator you can cause the loss yourself.נושא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.
עם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים. התוצאה תמיד 200,000.With synchronized, increment becomes a critical section: only one thread inside. 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.
עותק אחד, שני אנשים. כל אחד בודק copies > 0 ואז מוריד. בין הבדיקה להורדה (Thread.yield() נותן הזדמנות) השני יכול לעבור את הבדיקה גם. לפעמים שניהם "מקבלים" ו-copies יורד ל-1-.One copy, two people. Each checks copies > 0 then decrements. Between the check and the decrement (Thread.yield() gives a chance) the other can pass the check too. Sometimes both "get" it and copies drops to -1.נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter
LoanCounter סופר השאלות לפי כותר ובסך הכול. ארבעה דלפקים (threads) משאילים כל אחד 500 פעם, לסירוגין Dune ו-Emma. snapshot() מחזיר עותק. הדפיסו {Dune=1000, Emma=1000} total 2000.LoanCounter counts loans per title and in total. Four desks (threads) lend 500 times each, alternating Dune and Emma. snapshot() returns a copy. Print {Dune=1000, Emma=1000} total 2000.מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.race condition: A result that depends on the order threads run in.
המונחים של המפגשThis session's termsקטע קריטי: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.critical section: Code touching something shared, that only one thread should run at a time.
המונחים של המפגשThis session's termssynchronized: synchronized void inc() או `synchronized (lock) { ...synchronized: synchronized void inc() or `synchronized (lock) { ...
המונחים של המפגשThis session's termsמוניטור: המנעול המובנה של כל עצם ב-Java.monitor: The built-in lock every Java object has.
המונחים של המפגשThis session's termsreentrant: thread שכבר מחזיק מנעול יכול להיכנס אליו שוב (למשל מתודה synchronized שקוראת למתודה synchronized אחרת של אותו עצם) בלי לחסום את עצמו.reentrant: A thread already holding a lock can enter it again (e.g.
המונחים של המפגשThis session's termsבדיקה ואז פעולה: if (copies > 0) copies--;:check-then-act: if (copies > 0) copies--;:
המונחים של המפגשThis session's termsשני threads מגדילים מונה 100,000 פעמים כל אחד.Two threads increment a counter 100,000 times each.
count++ מאבד עדכוניםcount++ loses updatesהיינו מצפים ל-200,000.We'd expect 200,000.
count++ מאבד עדכוניםcount++ loses updatesהטבלה מראה מה באמת יצא ב-10 הרצות אמיתיות.The table shows what really came out in 10 real runs.
count++ מאבד עדכוניםcount++ loses updatesעם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים.With synchronized, increment becomes a critical section: only one thread inside.
synchronized: אחד בכל פעםsynchronized: one at a timeהתוצאה תמיד 200,000.The result is always 200,000.
synchronized: אחד בכל פעםsynchronized: one at a timeעותק אחד, שני אנשים.One copy, two people.
בדיקה ואז פעולהCheck, then actכל אחד בודק copies > 0 ואז מוריד.Each checks copies > 0 then decrements.
בדיקה ואז פעולהCheck, then actבין הבדיקה להורדה (Thread.yield() נותן הזדמנות) השני יכול לעבור את הבדיקה גם.Between the check and the decrement (Thread.yield() gives a chance) the other can pass the check too.
בדיקה ואז פעולהCheck, then actמדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter
הצעד של היום בפרויקט מדףToday's step in the Shelf projectלמה 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כי זה קריאה, חישוב וכתיבה, ו-thread אחר יכול להיכנס באמצעBecause it's a read, a calculation and a write, and another thread can slip in between
נכון.Right.שתי מתודות 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.הן לא רצות בו זמנית: שתיהן נועלות את thisThey don't run at the same time: both lock this
נכון.Right.מתודה 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
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.עובד: המנעול reentrantIt works: the lock is reentrant
נכון.Right.מונה בטוח, ארבעה threadsA safe counter, four threads
Counter עם synchronized על increment ועל get.Counter with synchronized on increment and get.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.בלוק synchronizedA synchronized block
- שני threads מוסיפים כל אחד 1000 מספרים ל-
ArrayList משותפת.Two threads each add 1000 numbers to a shared ArrayList.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: עדכונים אבודיםBug hunter: lost updates
- התוכנית מהתזכורת מדפיסה מספר שונה בכל הרצה, ובדרך כלל פחות מ-200,000.The program from the refresher prints a different number each run, usually less than 200,000.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.עשרה אנשים, שלושה עותקיםTen people, three copies
- ל-
Shelf יש 3 עותקים.Shelf has 3 copies.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter
LoanCounter סופר השאלות לפי כותר ובסך הכול.LoanCounter counts loans per title and in total.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.static synchronizedstatic synchronized
- מונה
static ומתודה static synchronized void visit() (נועלת את המחלקה).A static counter and a static synchronized void visit() method (it locks the class).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מנעול שנכנסים אליו שובA lock you can re-enter
transferIn היא synchronized וקוראת ל-deposit (גם synchronized) פעמיים.transferIn is synchronized and calls deposit (also synchronized) twice.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנו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
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.