חלקPart 6: Concurrency ו-ThreadsConcurrency & threads
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Race conditions, synchronized ומוניטוריםRace conditions, synchronized & monitors
למה count++ מאבד עדכונים, קטע קריטי, synchronized על מתודות ועל בלוקים, ומוניטורים.
Why count++ loses updates, critical sections, synchronized methods and blocks, and monitors.
הנקודות החשובותKey points
- מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.race condition: A result that depends on the order threads run in.
- קטע קריטי: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.critical section: Code touching something shared, that only one thread should run at a time.
- שני threads מגדילים מונה 100,000 פעמים כל אחד.Two threads increment a counter 100,000 times each.
- היינו מצפים ל-200,000.We'd expect 200,000.
- עם
synchronized,incrementנעשית קטע קריטי: רק thread אחד בפנים.Withsynchronized,incrementbecomes a critical section: only one thread inside. - התוצאה תמיד 200,000.The result is always 200,000.
- עותק אחד, שני אנשים.One copy, two people.
- כל אחד בודק
copies > 0ואז מוריד.Each checkscopies > 0then decrements. - מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter
מונחיםTerms
- מרוץ (race condition)race condition: תוצאה שתלויה בסדר שבו threads רצים.
count++הוא קריאה, חישוב וכתיבה, ושני threads יכולים לקרוא את אותו ערך לפני שמישהו כתב.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. - קטע קריטיcritical section: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.Code touching something shared, that only one thread should run at a time.
- synchronizedsynchronized:
synchronized void inc()אוsynchronized (lock) { ... }: רק thread אחד בכל פעם נכנס, והשאר מחכים (BLOCKED). גם מבטיח שהכתיבות נראות ל-thread הבא שנכנס.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. - מוניטורmonitor: המנעול המובנה של כל עצם ב-Java. מתודה synchronized נועלת את
this, ומתודה static synchronized נועלת את המחלקה.The built-in lock every Java object has. A synchronized method locksthis, and a static synchronized method locks the class. - reentrantreentrant: thread שכבר מחזיק מנעול יכול להיכנס אליו שוב (למשל מתודה synchronized שקוראת למתודה synchronized אחרת של אותו עצם) בלי לחסום את עצמו.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.
- בדיקה ואז פעולהcheck-then-act:
if (copies > 0) copies--;: בין הבדיקה לפעולה thread אחר יכול להיכנס. הבדיקה והפעולה חייבות להיות באותו קטע מוגן.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. - מרוץ (race condition)race condition: תוצאה שתלויה בסדר שבו threads רצים.
count++הוא קריאה, חישוב וכתיבה, ושני threads יכולים לקרוא את אותו ערך לפני שמישהו כתב.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. - קטע קריטיcritical section: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.Code touching something shared, that only one thread should run at a time.
- synchronizedsynchronized:
synchronized void inc()אוsynchronized (lock) { ... }: רק thread אחד בכל פעם נכנס, והשאר מחכים (BLOCKED). גם מבטיח שהכתיבות נראות ל-thread הבא שנכנס.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. - מוניטורmonitor: המנעול המובנה של כל עצם ב-Java. מתודה synchronized נועלת את
this, ומתודה static synchronized נועלת את המחלקה.The built-in lock every Java object has. A synchronized method locksthis, and a static synchronized method locks the class. - reentrantreentrant: thread שכבר מחזיק מנעול יכול להיכנס אליו שוב (למשל מתודה synchronized שקוראת למתודה synchronized אחרת של אותו עצם) בלי לחסום את עצמו.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.
- בדיקה ואז פעולהcheck-then-act:
if (copies > 0) copies--;: בין הבדיקה לפעולה thread אחר יכול להיכנס. הבדיקה והפעולה חייבות להיות באותו קטע מוגן.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.
Cheatsheet
count++ מאבד עדכוניםcount++ loses updates
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();synchronized: אחד בכל פעםsynchronized: one at a time
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();בדיקה ואז פעולהCheck, then act
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());שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|