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

JavaJava
33
חלק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.

או Ctrl+Por Ctrl+P

הנקודות החשובות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 while running.
  • בגלל ש-running הוא volatile, הוא רואה את ה-false של main ונעצר.Because running is volatile, it sees main's false and stops.
  • גם עם 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

מונחים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 before join(), 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 before join(), 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

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