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

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

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

  • מונחיםTerms
  • דגל עצירה volatileA volatile stop flag
  • volatile לא מספיק ל-count++volatile isn't enough for count++
  • פרסום נתון דרך volatilePublishing a value through volatile
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

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

פרויקט מדףShelf project

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

  • מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import

נראות: כל מעבד עובד עם עותקים שמורים (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.

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

גם עם volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד.Even with volatile, count++ is a separate read and write, so updates still get lost.

volatile נותן נראות, לא אטומיות.volatile gives visibility, not atomicity.

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.

מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import

מה volatile מבטיח?What does volatile guarantee?

  • שכל קריאה רואה את הכתיבה האחרונהThat every read sees the latest write
  • ש-x++ אטומיThat x++ is atomic
  • נעילהLocking
  • שה-thread רץ ראשוןThat the thread runs first

שכל קריאה רואה את הכתיבה האחרונהThat every read sees the latest write

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

5, מובטח5, guaranteed

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

עדיין עלולים לאבד עדכוניםUpdates can still be lost

עצירה של ייבואStopping an import

  • thread ייבוא עובד באצוות (כל אצווה sleep(5)) כל עוד running (volatile).An import thread works in batches (each sleep(5)) while running (volatile).

פרסום הגדרותPublishing settings

  • static volatile Config config = null.static volatile Config config = null.

צייד באגים: volatile לא מספיקBug hunter: volatile isn't enough

  • התוכנית מהתזכורת מאבדת עדכונים למרות volatile.The program from the refresher loses updates despite volatile.

join כגבולjoin as a boundary

  • thread ממלא מערך בריבועים 0–9.A thread fills an array with the squares 0–9.

מדף, צעד 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.

Double-checked lockingDouble-checked locking

  • Registry.get() יוצר מופע יחיד בעצלות:Registry.get() creates a single instance lazily:

volatile נושא איתו עודvolatile carries more along

  • כתבו את התוכנית מהתזכורת:Write the program from the refresher:

static volatile boolean running = true;static volatile boolean running = true;

record הוא בלתי משתנה, ולכן בטוח לפרסם אותו כך.A record is immutable, so it's safe to publish this way.

עם synchronized כבר לא צריך volatile: הנעילה נותנת גם נראות.With synchronized you no longer need volatile: the lock gives visibility too.

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

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

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

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