Race conditions, synchronized ומוניטוריםRace conditions, synchronized & monitors
למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים.
Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.
count++הוא קריאה, חישוב וכתיבה, ושני threads יכולים לקרוא את אותו ערך לפני שמישהו כתב.race condition: A result that depends on the order threads run in.count++is a read, a calculation and a write, and two threads can read the same value before anyone writes. - קטע קריטי: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.critical section: Code touching something shared, that only one thread should run at a time.
- synchronized:
synchronized void inc()אוsynchronized (lock) { ... }: רק thread אחד בכל פעם נכנס, והשאר מחכים (BLOCKED). גם מבטיח שהכתיבות נראות ל-thread הבא שנכנס.synchronized:synchronized void inc()orsynchronized (lock) { ... }: only one thread at a time gets in, the rest wait (BLOCKED). It also makes the writes visible to the next thread that enters. - מוניטור: המנעול המובנה של כל עצם ב-Java. מתודה synchronized נועלת את
this, ומתודה static synchronized נועלת את המחלקה.monitor: The built-in lock every Java object has. A synchronized method locksthis, and a static synchronized method locks the class. - reentrant: thread שכבר מחזיק מנעול יכול להיכנס אליו שוב (למשל מתודה synchronized שקוראת למתודה synchronized אחרת של אותו עצם) בלי לחסום את עצמו.reentrant: A thread already holding a lock can enter it again (e.g. a synchronized method calling another synchronized method of the same object) without blocking itself.
- בדיקה ואז פעולה:
if (copies > 0) copies--;: בין הבדיקה לפעולה thread אחר יכול להיכנס. הבדיקה והפעולה חייבות להיות באותו קטע מוגן.check-then-act:if (copies > 0) copies--;: between the check and the act another thread can slip in. The check and the act must be in the same protected section.
02count++ מאבד עדכוניםcount++ loses updates
שני threads מגדילים מונה 100,000 פעמים כל אחד. היינו מצפים ל-200,000. הטבלה מראה מה באמת יצא ב-10 הרצות אמיתיות. בסימולטור תוכלו לייצר את האיבוד בעצמכם.
Two threads increment a counter 100,000 times each. We'd expect 200,000. The table shows what really came out in 10 real runs. In the simulator you can cause the loss yourself.
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable job = () -> {
for (int i = 0; i < 100000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.get());
}
}
class Counter {
private int count = 0;
void increment() {
count++;
}
int get() {
return count;
}
}199922
10 הרצות אמיתיות בזמן בניית האתר (JDK 21):10 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
200000 | 3 |
138996 | 1 |
184123 | 1 |
172449 | 1 |
166763 | 1 |
199788 | 1 |
165719 | 1 |
177189 | 1 |
count++ בלי הגנה: נסו לאבד עדכוןcount++ unprotected: try to lose an update
03synchronized: אחד בכל פעםsynchronized: one at a time
עם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים. התוצאה תמיד 200,000.
With synchronized, increment becomes a critical section: only one thread inside. The result is always 200,000.
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable job = () -> {
for (int i = 0; i < 100000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.get());
}
}
class Counter {
private int count = 0;
synchronized void increment() {
count++;
}
synchronized int get() {
return count;
}
}200000
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
200000 | 5 |
count++ בתוך synchronizedcount++ inside synchronized
04בדיקה ואז פעולהCheck, then act
עותק אחד, שני אנשים. כל אחד בודק copies > 0 ואז מוריד. בין הבדיקה להורדה (Thread.yield() נותן הזדמנות) השני יכול לעבור את הבדיקה גם. לפעמים שניהם "מקבלים" ו-copies יורד ל-1-.
One copy, two people. Each checks copies > 0 then decrements. Between the check and the decrement (Thread.yield() gives a chance) the other can pass the check too. Sometimes both "get" it and copies drops to -1.
import java.util.ArrayList;
import java.util.List;
public class Main {
static int copies = 1;
static final List<String> got = new ArrayList<>();
static void tryLend(String who) {
if (copies > 0) {
Thread.yield();
copies--;
synchronized (got) {
got.add(who);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(() -> tryLend("Noa"));
Thread b = new Thread(() -> tryLend("Avi"));
a.start();
b.start();
a.join();
b.join();
System.out.println("copies=" + copies + " lent to " + got.size());
}
}copies=0 lent to 1
20 הרצות אמיתיות בזמן בניית האתר (JDK 21):20 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
copies=0 lent to 1 | 20 |
בדיקה ואז פעולה: שניים לוקחים את העותק האחרוןCheck, then act: two people take the last copy
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
LoanCounter סופר השאלות לפי כותר ובסך הכול. ארבעה דלפקים (threads) משאילים כל אחד 500 פעם, לסירוגין Dune ו-Emma. snapshot() מחזיר עותק. הדפיסו {Dune=1000, Emma=1000} total 2000.
LoanCounter counts loans per title and in total. Four desks (threads) lend 500 times each, alternating Dune and Emma. snapshot() returns a copy. Print {Dune=1000, Emma=1000} total 2000.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.