חלקPart 6: Concurrency ו-ThreadsConcurrency & threads
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
volatile ו-Java Memory Modelvolatile & the Java Memory Model
נראות (visibility), happens-before, volatile, ומתי הוא לא מספיק.
Visibility, happens-before, volatile, and when it isn't enough.
הנקודות החשובותKey points
- נראות: כל מעבד עובד עם עותקים שמורים (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: - ה-worker מסתובב כל עוד
running.The worker spins whilerunning. - בגלל ש-
runningהוא volatile, הוא רואה את ה-falseשל main ונעצר.Becauserunningis volatile, it sees main'sfalseand stops. - גם עם
volatile,count++הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד.Even withvolatile,count++is a separate read and write, so updates still get lost. - volatile נותן נראות, לא אטומיות.volatile gives visibility, not atomicity.
dataלא volatile, אבל נכתב לפני הכתיבה ל-ready(שכן volatile).dataisn't volatile, but it's written before the write toready(which is volatile).- לפי happens-before, מי שרואה
ready == trueרואה גםdata = 42.By happens-before, whoever seesready == truealso seesdata = 42. - מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import
מונחיםTerms
- נראותvisibility: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה. בלי סנכרון, thread עלול להמשיך לראות ערך ישן לנצח.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.
- volatilevolatile:
volatile boolean running: כל קריאה רואה את הכתיבה האחרונה, וכל מה שנכתב לפני כתיבה ל-volatile נראה למי שקורא אותו. לא נותן אטומיות:count++עדיין לא בטוח.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-beforehappens-before: כלל ב-Java שמבטיח שכתיבה נראית לקריאה:
start()לפני כל מה שה-thread עושה, כל מה שה-thread עשה לפניjoin(), כתיבה ל-volatile לפני קריאה שלו, ושחרור מנעול לפני הנעילה הבאה.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 ModelJava Memory Model: החלק במפרט של Java שמגדיר מה thread אחד רשאי לראות מהכתיבות של אחר. בלי happens-before, אין הבטחה.The part of the Java spec defining what one thread may see of another's writes. Without happens-before, there's no promise.
- נראותvisibility: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה. בלי סנכרון, thread עלול להמשיך לראות ערך ישן לנצח.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.
- volatilevolatile:
volatile boolean running: כל קריאה רואה את הכתיבה האחרונה, וכל מה שנכתב לפני כתיבה ל-volatile נראה למי שקורא אותו. לא נותן אטומיות:count++עדיין לא בטוח.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-beforehappens-before: כלל ב-Java שמבטיח שכתיבה נראית לקריאה:
start()לפני כל מה שה-thread עושה, כל מה שה-thread עשה לפניjoin(), כתיבה ל-volatile לפני קריאה שלו, ושחרור מנעול לפני הנעילה הבאה.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 ModelJava Memory Model: החלק במפרט של Java שמגדיר מה thread אחד רשאי לראות מהכתיבות של אחר. בלי happens-before, אין הבטחה.The part of the Java spec defining what one thread may see of another's writes. Without happens-before, there's no promise.
Cheatsheet
דגל עצירה volatileA volatile stop flag
Thread worker = new Thread(() -> {
long spins = 0;
while (running) {
spins++;
}
System.out.println("worker stopped");
});
worker.start();
Thread.sleep(50);
running = false;volatile לא מספיק ל-count++volatile isn't enough for count++
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();פרסום נתון דרך volatilePublishing a value through volatile
Thread reader = new Thread(() -> {
while (!ready) {
Thread.onSpinWait();
}
System.out.println("data=" + data);
});
reader.start();
data = 42;
ready = true;
reader.join();שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|