נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
volatile ו-Java Memory Modelvolatile & the Java Memory Model
מפגש 33: נראות (visibility), happens-before, volatile, ומתי הוא לא מספיק.Session 33: Visibility, happens-before, volatile, and when it isn't enough.
נראות (visibility), happens-before, volatile, ומתי הוא לא מספיק. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Visibility, happens-before, volatile, and when it isn't enough. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- דגל עצירה volatileA volatile stop flag
- volatile לא מספיק ל-count++volatile isn't enough for count++
- פרסום נתון דרך volatilePublishing a value through volatile
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- נראות: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה.visibility: Each CPU works with cached copies, and the JIT can move a read out of a loop.
- volatile:
volatile boolean running:volatile: volatile boolean running: - happens-before: כלל ב-Java שמבטיח שכתיבה נראית לקריאה:happens-before: A Java rule guaranteeing a write is visible to a read:
- Java Memory Model: החלק במפרט של Java שמגדיר מה thread אחד רשאי לראות מהכתיבות של אחר.Java Memory Model: The part of the Java spec defining what one thread may see of another's writes.
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
דגל עצירה volatileA volatile stop flag
דגל עצירה volatileA volatile stop flag
- ה-worker מסתובב כל עוד
running.The worker spins while running. - בגלל ש-
running הוא volatile, הוא רואה את ה-false של main ונעצר.Because running is volatile, it sees main's false and stops. - בלי volatile התוכנית עלולה לא להיעצר לעולם (ה-JIT מוציא את הקריאה מהלולאה), ולכן את הגרסה הזו אנחנו רק מדמים, לא מריצים.Without volatile the program might never stop (the JIT moves the read out of the loop), so we only simulate that version, never run it.
ה-worker מסתובב כל עוד running. בגלל ש-running הוא volatile, הוא רואה את ה-false של main ונעצר. בלי volatile התוכנית עלולה לא להיעצר לעולם (ה-JIT מוציא את הקריאה מהלולאה), ולכן את הגרסה הזו אנחנו רק מדמים, לא מריצים. בסימולטור השני תראו אותה נתקעת.The worker spins while running. Because running is volatile, it sees main's false and stops. Without volatile the program might never stop (the JIT moves the read out of the loop), so we only simulate that version, never run it. In the second simulator you'll see it stuck.נושאTopic 3
volatile לא מספיק ל-count++volatile isn't enough for count++
volatile לא מספיק ל-count++volatile isn't enough for count++
- גם עם
volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד.Even with volatile, count++ is a separate read and write, so updates still get lost. - volatile נותן נראות, לא אטומיות.volatile gives visibility, not atomicity.
גם עם volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד. volatile נותן נראות, לא אטומיות.Even with volatile, count++ is a separate read and write, so updates still get lost. volatile gives visibility, not atomicity.נושאTopic 4
פרסום נתון דרך volatilePublishing a value through volatile
פרסום נתון דרך volatilePublishing a value through volatile
data לא volatile, אבל נכתב לפני הכתיבה ל-ready (שכן volatile).data isn't volatile, but it's written before the write to ready (which is volatile).- לפי happens-before, מי שרואה
ready == true רואה גם data = 42.By happens-before, whoever sees ready == true also sees data = 42.
data לא volatile, אבל נכתב לפני הכתיבה ל-ready (שכן volatile). לפי happens-before, מי שרואה ready == true רואה גם data = 42.data isn't volatile, but it's written before the write to ready (which is volatile). By happens-before, whoever sees ready == true also sees data = 42.נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import
Importer מייבא 1000 שורות (2ms לשורה) ובודק לפני כל שורה את cancelled (volatile). main מבטל אחרי 30ms. הדפיסו cancelled: true ואז stopped early: true.Importer imports 1000 lines (2ms per line) and checks cancelled (volatile) before each line. main cancels after 30ms. Print cancelled: true then stopped early: true.נראות: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה.visibility: Each CPU works with cached copies, and the JIT can move a read out of a loop.
המונחים של המפגשThis session's termsvolatile: volatile boolean running:volatile: volatile boolean running:
המונחים של המפגשThis session's termshappens-before: כלל ב-Java שמבטיח שכתיבה נראית לקריאה:happens-before: A Java rule guaranteeing a write is visible to a read:
המונחים של המפגשThis session's termsJava Memory Model: החלק במפרט של Java שמגדיר מה thread אחד רשאי לראות מהכתיבות של אחר.Java Memory Model: The part of the Java spec defining what one thread may see of another's writes.
המונחים של המפגשThis session's termsה-worker מסתובב כל עוד running.The worker spins while running.
דגל עצירה volatileA volatile stop flagבגלל ש-running הוא volatile, הוא רואה את ה-false של main ונעצר.Because running is volatile, it sees main's false and stops.
דגל עצירה volatileA volatile stop flagבלי volatile התוכנית עלולה לא להיעצר לעולם (ה-JIT מוציא את הקריאה מהלולאה), ולכן את הגרסה הזו אנחנו רק מדמים, לא מריצים.Without volatile the program might never stop (the JIT moves the read out of the loop), so we only simulate that version, never run it.
דגל עצירה volatileA volatile stop flagגם עם volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד.Even with volatile, count++ is a separate read and write, so updates still get lost.
volatile לא מספיק ל-count++volatile isn't enough for count++volatile נותן נראות, לא אטומיות.volatile gives visibility, not atomicity.
volatile לא מספיק ל-count++volatile isn't enough for count++data לא volatile, אבל נכתב לפני הכתיבה ל-ready (שכן volatile).data isn't volatile, but it's written before the write to ready (which is volatile).
פרסום נתון דרך volatilePublishing a value through volatileלפי happens-before, מי שרואה ready == true רואה גם data = 42.By happens-before, whoever sees ready == true also sees data = 42.
פרסום נתון דרך volatilePublishing a value through volatileמדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import
הצעד של היום בפרויקט מדףToday's step in the Shelf projectמה volatile מבטיח?What does volatile guarantee?
- שכל קריאה רואה את הכתיבה האחרונהThat every read sees the latest write
- ש-
x++ אטומיThat x++ is atomic - נעילהLocking
- שה-thread רץ ראשוןThat the thread runs first
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.שכל קריאה רואה את הכתיבה האחרונהThat every read sees the latest write
נכון: נראות.Right: visibility.main כותב x = 5 ואז t.start(). ה-thread קורא x. מה הוא רואה?main writes x = 5 then t.start(). The thread reads x. What does it see?
- 5, מובטח5, guaranteed
- אולי 0Maybe 0
- שגיאהAn error
- תלוי ב-volatileIt depends on volatile
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.5, מובטח5, guaranteed
נכון: start יוצר happens-before.Right: start creates happens-before.volatile int count ושני threads עושים count++. התוצאה?volatile int count and two threads doing count++. The result?
- עדיין עלולים לאבד עדכוניםUpdates can still be lost
- תמיד נכונהAlways right
- deadlockdeadlock
- לא מתקמפלDoesn't compile
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.עדיין עלולים לאבד עדכוניםUpdates can still be lost
נכון.Right.עצירה של ייבואStopping an import
- thread ייבוא עובד באצוות (כל אצווה
sleep(5)) כל עוד running (volatile).An import thread works in batches (each sleep(5)) while running (volatile).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.פרסום הגדרותPublishing settings
static volatile Config config = null.static volatile Config config = null.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: volatile לא מספיקBug hunter: volatile isn't enough
- התוכנית מהתזכורת מאבדת עדכונים למרות
volatile.The program from the refresher loses updates despite volatile.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.join כגבולjoin as a boundary
- thread ממלא מערך בריבועים 0–9.A thread fills an array with the squares 0–9.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import
Importer מייבא 1000 שורות (2ms לשורה) ובודק לפני כל שורה את cancelled (volatile).Importer imports 1000 lines (2ms per line) and checks cancelled (volatile) before each line.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.Double-checked lockingDouble-checked locking
Registry.get() יוצר מופע יחיד בעצלות:Registry.get() creates a single instance lazily:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.volatile נושא איתו עודvolatile carries more along
- כתבו את התוכנית מהתזכורת:Write the program from the refresher:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.static volatile boolean running = true;static volatile boolean running = true;
עצירה של ייבואStopping an importrecord הוא בלתי משתנה, ולכן בטוח לפרסם אותו כך.A record is immutable, so it's safe to publish this way.
פרסום הגדרותPublishing settingsעם synchronized כבר לא צריך volatile: הנעילה נותנת גם נראות.With synchronized you no longer need volatile: the lock gives visibility too.
צייד באגים: volatile לא מספיקBug hunter: volatile isn't enoughמה למדנוWhat we learned
- נראות: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה.visibility: Each CPU works with cached copies, and the JIT can move a read out of a loop.
- ה-worker מסתובב כל עוד
running.The worker spins while running. - גם עם
volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד.Even with volatile, count++ is a separate read and write, so updates still get lost. data לא volatile, אבל נכתב לפני הכתיבה ל-ready (שכן volatile).data isn't volatile, but it's written before the write to ready (which is volatile).- מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.