volatile ו-Java Memory Modelvolatile & the Java Memory Model
נראות (visibility), happens-before, volatile, ומתי הוא לא מספיק.
Visibility, happens-before, volatile, and when it isn't enough.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-IntelliJ ולסמן פתרתי. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in IntelliJ and mark I solved it. Progress is saved.
חימום: 3 שאלותWarm-up: 3 questions
תרגיליםExercises
תרגילExercise 1
עצירה של ייבואStopping an import
thread ייבוא עובד באצוות (כל אצווה sleep(5)) כל עוד running (volatile). main מחכה 40ms, מכבה את הדגל ומחכה עם join. הדפיסו importer stopped: true ואז done.
An import thread works in batches (each sleep(5)) while running (volatile). main waits 40ms, turns the flag off and waits with join. Print importer stopped: true then done.
איך הפלט אמור להיראות?What should the output look like?
importer stopped: true
done
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
static volatile Config config = null. ה-reader מחכה (Thread.onSpinWait()) עד שהשדה לא null ומדפיס theme=dark size=14. main יוצר new Config("dark", 14) ומפרסם.
static volatile Config config = null. The reader waits (Thread.onSpinWait()) until the field isn't null and prints theme=dark size=14. main creates new Config("dark", 14) and publishes it.
איך הפלט אמור להיראות?What should the output look like?
theme=dark size=14
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:record הוא בלתי משתנה, ולכן בטוח לפרסם אותו כך.A record is immutable, so it's safe to publish this way.
צייד באגים: volatile לא מספיקBug hunter: volatile isn't enough
התוכנית מהתזכורת מאבדת עדכונים למרות volatile. תקנו עם מתודה static synchronized void inc() כך שתמיד יודפס 200000.
The program from the refresher loses updates despite volatile. Fix it with a static synchronized void inc() method so it always prints 200000.
איך הפלט אמור להיראות?What should the output look like?
200000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:עם synchronized כבר לא צריך volatile: הנעילה נותנת גם נראות.With synchronized you no longer need volatile: the lock gives visibility too.
thread ממלא מערך בריבועים 0–9. אחרי join, main סוכם (בלי volatile ובלי synchronized) ומדפיס 285. למה זה בטוח? בגלל happens-before של join.
A thread fills an array with the squares 0–9. After join, main sums it (no volatile, no synchronized) and prints 285. Why is it safe? Because of join's happens-before.
איך הפלט אמור להיראות?What should the output look like?
285
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:כל מה שה-thread כתב נראה אחרי join.Everything the thread wrote is visible after join.
מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import
פרויקט מלווהCompanion 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.
איך הפלט אמור להיראות?What should the output look like?
cancelled: true
stopped early: true
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:גם imported volatile, כי main קורא אותו.imported is volatile too, because main reads it.
רמזHint 2:כאן רק thread אחד כותב ל-imported, ולכן ++ בסדר.Here only one thread writes imported, so ++ is fine.
Registry.get() יוצר מופע יחיד בעצלות: בודק בלי נעילה, ורק אם null נועל ובודק שוב. השדה חייב להיות volatile, אחרת thread אחר עלול לראות עצם שנבנה חלקית. הדפיסו same instance: true, created 1.
Registry.get() creates a single instance lazily: it checks without locking, and only if null locks and checks again. The field must be volatile, or another thread might see a half-built object. Print same instance: true, created 1.
איך הפלט אמור להיראות?What should the output look like?
same instance: true, created 1
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:הבדיקה השנייה בתוך הנעילה מונעת יצירה כפולה.The second check inside the lock prevents a double creation.
כתבו את התוכנית מהתזכורת: data רגיל, ready volatile. main כותב data = 42 ואז ready = true. ה-reader מחכה ל-ready ומדפיס data=42. הסבירו לעצמכם למה זה מובטח.
Write the program from the refresher: a plain data, a volatile ready. main writes data = 42 then ready = true. The reader waits for ready and prints data=42. Explain to yourself why that's guaranteed.
איך הפלט אמור להיראות?What should the output look like?
data=42
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:אם תהפכו את הסדר (ready לפני data), אין הבטחה.If you swap the order (ready before data), there's no promise.