volatile ו-Java Memory Modelvolatile & the Java Memory Model
נראות (visibility), happens-before, volatile, ומתי הוא לא מספיק.
Visibility, happens-before, volatile, and when it isn't enough.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- נראות: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה. בלי סנכרון, thread עלול להמשיך לראות ערך ישן לנצח.visibility: Each CPU works with cached copies, and the JIT can move a read out of a loop. Without synchronization, a thread may keep seeing an old value forever.
- volatile:
volatile boolean running: כל קריאה רואה את הכתיבה האחרונה, וכל מה שנכתב לפני כתיבה ל-volatile נראה למי שקורא אותו. לא נותן אטומיות:count++עדיין לא בטוח.volatile:volatile boolean running: every read sees the latest write, and whatever was written before a volatile write is visible to whoever reads it. It gives no atomicity:count++still isn't safe. - happens-before: כלל ב-Java שמבטיח שכתיבה נראית לקריאה:
start()לפני כל מה שה-thread עושה, כל מה שה-thread עשה לפניjoin(), כתיבה ל-volatile לפני קריאה שלו, ושחרור מנעול לפני הנעילה הבאה.happens-before: A Java rule guaranteeing a write is visible to a read:start()before everything the thread does, everything the thread did beforejoin(), a volatile write before its read, and an unlock before the next lock. - Java Memory Model: החלק במפרט של Java שמגדיר מה thread אחד רשאי לראות מהכתיבות של אחר. בלי happens-before, אין הבטחה.Java Memory Model: The part of the Java spec defining what one thread may see of another's writes. Without happens-before, there's no promise.
02דגל עצירה volatileA volatile stop flag
ה-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.
public class Main {
static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long spins = 0;
while (running) {
spins++;
}
System.out.println("worker stopped");
});
worker.start();
Thread.sleep(50);
running = false;
worker.join();
System.out.println("main done");
}
}worker stopped main done
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
worker stopped
main done | 5 |
volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
בלי volatile: דגל עצירה שלא נראהWithout volatile: a stop flag nobody sees
03volatile לא מספיק ל-count++volatile isn't enough for count++
גם עם volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד. volatile נותן נראות, לא אטומיות.
Even with volatile, count++ is a separate read and write, so updates still get lost. volatile gives visibility, not atomicity.
public class Main {
static volatile int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 100000; i++) {
count++;
}
};
Thread a = new Thread(job);
Thread b = new Thread(job);
a.start();
b.start();
a.join();
b.join();
System.out.println(count);
}
}163534
10 הרצות אמיתיות בזמן בניית האתר (JDK 21):10 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
191225 | 1 |
153119 | 1 |
170941 | 1 |
173413 | 1 |
176021 | 1 |
187776 | 1 |
191353 | 1 |
153370 | 1 |
198362 | 1 |
165434 | 1 |
count++ בלי הגנה: נסו לאבד עדכוןcount++ unprotected: try to lose an update
04פרסום נתון דרך volatilePublishing a value through volatile
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.
public class Main {
static int data = 0;
static volatile boolean ready = false;
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
while (!ready) {
Thread.onSpinWait();
}
System.out.println("data=" + data);
});
reader.start();
data = 42;
ready = true;
reader.join();
}
}data=42
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
data=42 | 5 |
volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
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.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.