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

JavaJava
38
חלקPart 6: Concurrency ו-ThreadsConcurrency & threads כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

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 says Found one Java-level deadlock when 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.

Main.java
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();
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
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 deadlock4
T2 gave up: would have been a deadlock T1 gave up: would have been a deadlock1
סדר מנעולים הפוך: 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.

Main.java
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();
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
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 both5
אותו סדר מנעולים: אין 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.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

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.

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