Deadlock, livelock ו-starvationDeadlock, livelock & starvation
איך threads נתקעים, איך מאבחנים עם jstack ו-thread dump, ואיך מונעים: סדר מנעולים, tryLock וזמנים קצובים.
How threads get stuck, how to diagnose with jstack and a thread dump, and how to prevent it: lock ordering, tryLock and timeouts.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- deadlock: שני threads (או יותר) שכל אחד מחזיק משהו שהשני צריך, ומחכה לו. אף אחד לא יתקדם לעולם, והתוכנית "קופאת" בלי שגיאה.deadlock: Two (or more) threads each holding something the other needs, and waiting for it. Nobody will ever move, and the program "freezes" with no error.
- סדר נעילה: אם כולם נועלים מנעולים באותו סדר (למשל לפי id), מעגל המתנה לא יכול להיווצר.lock ordering: If everyone takes locks in the same order (say by id), a waiting cycle can't form.
- livelock: threads לא תקועים, אבל כל הזמן מוותרים זה לזה ומנסים שוב, ולכן לא מתקדמים. פתרון: המתנה אקראית לפני ניסיון חוזר.livelock: Threads aren't stuck, but keep giving way to each other and retrying, so they never progress. Fix: a random wait before retrying.
- הרעבה: thread שכמעט אף פעם לא מקבל את המנעול כי אחרים תמיד מקדימים. מנעול הוגן (
new ReentrantLock(true)) משרת לפי סדר הגעה.starvation: A thread that almost never gets the lock because others always get there first. A fair lock (new ReentrantLock(true)) serves in order of arrival. - thread dump: תמונה של כל ה-threads ומה כל אחד מחזיק ומחכה לו.
jstack <pid>(או Ctrl+Break) מדפיס אותה, וכותבFound one Java-level deadlockכשיש.thread dump: A snapshot of every thread and what it holds and waits for.jstack <pid>(or Ctrl+Break) prints it, and saysFound one Java-level deadlockwhen there is one.
02נעילה בסדר הפוךLocking in opposite orders
T1 נועל A ואז רוצה B; T2 נועל B ואז רוצה A. בלי זמן קצוב זה deadlock (את הגרסה הזו רק מדמים, כי היא הייתה תוקעת את הבנייה). כאן tryLock(200ms) מגלה שמשהו לא בסדר ומוותר. בסימולטור נסו לייצר את התקיעה בעצמכם.
T1 locks A then wants B; T2 locks B then wants A. Without a timeout that's a deadlock (we only simulate that version, since it would hang the build). Here tryLock(200ms) notices something's wrong and backs off. In the simulator, try causing the freeze yourself.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static final ReentrantLock a = new ReentrantLock();
static final ReentrantLock b = new ReentrantLock();
static void work(String name, ReentrantLock first, ReentrantLock second) {
first.lock();
try {
sleep(50);
if (second.tryLock(200, TimeUnit.MILLISECONDS)) {
second.unlock();
System.out.println(name + " got both");
} else {
System.out.println(name + " gave up: would have been a deadlock");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
first.unlock();
}
}
static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> work("T1", a, b));
Thread t2 = new Thread(() -> work("T2", b, a));
t1.start();
t2.start();
t1.join();
t2.join();
}
}T2 gave up: would have been a deadlock T1 gave up: would have been a deadlock
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
T1 gave up: would have been a deadlock
T2 gave up: would have been a deadlock | 4 |
T2 gave up: would have been a deadlock
T1 gave up: would have been a deadlock | 1 |
סדר מנעולים הפוך: deadlockOpposite lock order: deadlock
03אותו סדר לכולםThe same order for everyone
שני ה-threads נועלים קודם A ואז B. מעגל לא יכול להיווצר, ושניהם תמיד מצליחים.
Both threads lock A first and then B. A cycle can't form, and both always succeed.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static final ReentrantLock a = new ReentrantLock();
static final ReentrantLock b = new ReentrantLock();
static void work(String name, ReentrantLock first, ReentrantLock second) {
first.lock();
try {
sleep(50);
if (second.tryLock(200, TimeUnit.MILLISECONDS)) {
second.unlock();
System.out.println(name + " got both");
} else {
System.out.println(name + " gave up: would have been a deadlock");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
first.unlock();
}
}
static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> work("T1", a, b));
Thread t2 = new Thread(() -> work("T2", a, b));
t1.start();
t2.start();
t1.join();
t2.join();
}
}T2 got both T1 got both
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
T1 got both
T2 got both | 5 |
אותו סדר מנעולים: אין deadlockThe same lock order: no deadlock
04הצעד של היום בפרויקט מדףToday's step in the Shelf project
Shelf.lend(from, to) מעבירה ספר אחד בין מדפים, עם ReentrantLock לכל מדף, תמיד לפי id (הקטן קודם). שני threads מעבירים בכיוונים הפוכים. מ-home=3 ו-club=1: home=3 club=1.
Shelf.lend(from, to) moves one book between shelves, with a ReentrantLock per shelf, always by id (smaller first). Two threads move in opposite directions. From home=3 and club=1: home=3 club=1.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.